0% found this document useful (0 votes)
13 views20 pages

New OOP

The document provides a comprehensive overview of key Object-Oriented Programming (OOP) concepts, including definitions and examples for objects, classes, encapsulation, inheritance, polymorphism, abstraction, and more. It covers various programming techniques such as exception handling, templates, operator overloading, and file handling in C++. Additionally, it explains the relationships between classes like association, aggregation, and composition, alongside construction and destruction processes in inheritance.

Uploaded by

m.physicist321
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views20 pages

New OOP

The document provides a comprehensive overview of key Object-Oriented Programming (OOP) concepts, including definitions and examples for objects, classes, encapsulation, inheritance, polymorphism, abstraction, and more. It covers various programming techniques such as exception handling, templates, operator overloading, and file handling in C++. Additionally, it explains the relationships between classes like association, aggregation, and composition, alongside construction and destruction processes in inheritance.

Uploaded by

m.physicist321
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

1.

Object in OOP
Definition

An object is an instance of a class that represents a real-world entity. It contains data (attributes)
and methods (functions) that define its behavior.

Example:

An object of a Car class could have attributes like color and a method like drive().

Car myCar;
myCar.color = "Red";
myCar.drive();

2. Class in OOP
Definition

A class is a blueprint or template for creating objects. It defines the attributes (data members)
and behaviors (methods) that the objects will have.

Example:

A Student class could define attributes like name and age and a method like display().

class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

3. Encapsulation
Definition

Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate
on the data into a single unit (class). It also restricts direct access to some of the object's
components.

Example:
Using private members and public methods in a BankAccount class ensures controlled access.

class BankAccount {
private:
int balance;
public:
void deposit(int amount) { balance += amount; }
};

4. Inheritance
Definition

Inheritance allows a class (child) to inherit attributes and methods from another class (parent). It
promotes code reuse and represents an "is-a" relationship.

Example:

A Dog class inherits common features from an Animal class.

class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};

class Dog : public Animal {


public:
void bark() { cout << "Barking..." << endl; }
};

5. Polymorphism
Definition

Polymorphism allows objects of different classes to be treated as objects of a common base class.
It enables methods to behave differently based on the object that invokes them.

Example:

A Dog and a Cat class can override the sound() method from a base Animal class.

class Animal {
public:
virtual void sound() { cout << "Animal sound" << endl; }
};

class Dog : public Animal {


public:
void sound() override { cout << "Bark" << endl; }
};

6. Abstraction
Definition

Abstraction hides unnecessary details and shows only essential features. It simplifies complex
systems by modeling classes appropriate to the problem.

Example:

A Calculator class exposes only the add() method without revealing how addition is
performed.

class Calculator {
public:
int add(int a, int b) { return a + b; }
};

7. Constructor
Definition

A constructor is a special method that is automatically called when an object is created. It is used
to initialize the object's data members.

Example:

A Car class initializes its brand attribute when an object is created.

class Car {
public:
string brand;
Car(string b) { brand = b; }
};

8. Destructor
Definition

A destructor is a special method that is automatically called when an object is destroyed. It is


used to release resources.

Example:
A Student class destructor displays a message when an object is destroyed.

class Student {
public:
~Student() { cout << "Object destroyed" << endl; }
};

9. Friend Function
Definition

A friend function is a function that is not a member of a class but can access its private and
protected members.

Example:

A friend function printLength() accesses the private member length of a Box class.

class Box {
private:
int length;
public:
friend void printLength(Box b);
};

10. Function Overloading


Definition

Function overloading allows multiple functions with the same name but different parameters.

Example:

The print() function is overloaded to handle different data types.

void print(int i) { cout << "Integer: " << i << endl; }


void print(double d) { cout << "Double: " << d << endl; }

11. Operator Overloading


Definition

Operator overloading allows defining custom behavior for operators like +, -, *, etc., for user-
defined types.
Example:

A Complex class overloads the + operator to add two complex numbers.

class Complex {
public:
int real, imag;
Complex operator + (Complex const &obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
};

12. Exception Handling


Definition

Exception handling allows dealing with runtime errors using try, catch, and throw blocks.

Example:

A division operation throws an exception when dividing by zero.

try {
if (b == 0) throw "Division by zero!";
cout << a / b << endl;
} catch (const char* msg) {
cout << "Error: " << msg << endl;
}

13. Templates
Definition

Templates allow writing generic functions and classes that can work with any data type.

Example:

A generic add() function can work with integers, floats, or other data types.

template <typename T>


T add(T a, T b) { return a + b; }

14. Dynamic Binding


Definition

Dynamic binding (or late binding) allows the method to be called to be determined at runtime,
based on the object type.

Example:

A base class pointer calls the overridden method of the derived class.

class Animal {
public:
virtual void sound() { cout << "Animal sound" << endl; }
};

class Dog : public Animal {


public:
void sound() override { cout << "Bark" << endl; }
};

15. Abstract Class


Definition

An abstract class is a class that cannot be instantiated and contains at least one pure virtual
function.

Example:

A Shape class defines a pure virtual function draw() that derived classes must implement.

class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

16. Static Members


Definition

Static members are shared among all objects of a class. They belong to the class itself, not to any
specific object.

Example:

A Counter class uses a static data member count to keep track of the number of objects created.
class Counter {
public:
static int count;
Counter() { count++; }
};

int Counter::count = 0;

17. Association
Definition

Association is a relationship between two classes where one class uses or interacts with another
class.

Example:

A Driver class interacts with a Car class.

class Driver {
public:
void drive(Car car) { cout << "Driving " << car.model << endl; }
};

18. Aggregation
Definition

Aggregation is a "has-a" relationship where one class contains objects of another class, but the
contained objects can exist independently.

Example:

A University class contains Department objects that can exist independently.

class Department {
public:
string name;
};

class University {
public:
vector<Department> departments;
};

19. Composition
Definition

Composition is a strong "has-a" relationship where the contained objects cannot exist
independently of the container.

Example:

A Car class contains an Engine object that cannot exist without the Car.

class Engine {
public:
string type;
};

class Car {
public:
Engine engine; // Engine cannot exist without Car
};

20. Pointers to Objects


Definition

A pointer to an object stores the memory address of an object, allowing indirect access to its
members.

Example:

A pointer to a Car object calls its drive() method.

Car myCar;
Car* ptr = &myCar;
ptr->drive();

21. Dynamic Memory Allocation


Definition

Dynamic memory allocation allows allocating memory for objects at runtime using new and
releasing it using delete.

Example:

An integer is allocated dynamically and then deleted.

int* ptr = new int;


*ptr = 10;
delete ptr;

22. Copy Constructor


Definition

A copy constructor is used to create a new object as a copy of an existing object.

Example:

A Student class defines a copy constructor to copy data from another object.

class Student {
public:
Student(const Student &obj) { name = obj.name; }
};

23. Virtual Destructor


Definition

A virtual destructor ensures that the destructor of the derived class is called when deleting an
object through a base class pointer.

Example:

A base class defines a virtual destructor to properly release resources of the derived class.

class Base {
public:
virtual ~Base() { cout << "Base destructor" << endl; }
};

24. Streams in C++


Definition

Streams are used for input/output operations in C++. Examples include cin, cout, and file
streams.

Example:

A program reads a value using cin and writes it using cout.


int x;
cout << "Enter a number: ";
cin >> x;
cout << "You entered: " << x << endl;

25. Default Values for Functions


Definition: Default values for functions allow you to assign a value to a function's parameter in
advance. If no argument is provided for that parameter, the default value is used.

Example: A function printMessage() with a default value for the message parameter:

void printMessage(string message = "Hello, World!") {


cout << message << endl;
}

26. Inline Functions


Definition: An inline function is a function where the function body is expanded in place at the
point where it is called, reducing the overhead of function calls.

Example: An inline function to calculate the square of a number:

inline int square(int x) { return x * x; }

27. Open Parameter List


Definition: An open parameter list allows a function to accept a variable number of arguments,
making it flexible for handling diverse inputs.

Example: A function sum() using std::initializer_list to accept multiple arguments:

int sum(initializer_list<int> numbers) {


int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
28. References in C++
Definition: A reference is an alias for an existing variable. It allows you to access and modify
the original variable directly without creating a copy.

Example: A reference ref pointing to variable a:

int a = 10;
int &ref = a;
ref = 20; // Modifies a

29. Friend Classes


Definition: A friend class is a class that can access the private and protected members of another
class. It is declared using the friend keyword.

Example: A FriendClass accessing private data of a Box class:

class Box {
private:
int length;
friend class FriendClass;
};

30. Static Class Members


Definition: Static members in a class are shared among all objects of the class. They belong to
the class itself, not to any specific object.

Example: A Counter class uses a static member count to track object creation:

class Counter {
public:
static int count;
Counter() { count++; }
};

31. Generalization and Specialization


Definition:
 Generalization: Combining common features of multiple classes into a single parent
class.
 Specialization: Adding unique features to a derived class to make it more specific.

Example: A Vehicle class generalized from Car and Bike, while Car specializes further with
unique features:

class Vehicle {
public:
void start() { cout << "Vehicle started" << endl; }
};
class Car : public Vehicle {
public:
void drive() { cout << "Car is driving" << endl; }
};

32. Construction and Destruction in Inheritance


Definition: When a derived class object is created, the base class constructor is called first,
followed by the derived class constructor. During destruction, the derived class destructor is
called first, followed by the base class destructor.

Example: A Derived object outputs the construction and destruction order:

class Base {
public:
Base() { cout << "Base constructor" << endl; }
~Base() { cout << "Base destructor" << endl; }
};
class Derived : public Base {
public:
Derived() { cout << "Derived constructor" << endl; }
~Derived() { cout << "Derived destructor" << endl; }
};

33. Pointing Down the Hierarchy


Definition: Pointing down the hierarchy refers to using a base class pointer or reference to point
to objects of derived classes, enabling polymorphism.

Example: A base class pointer points to a derived class object and calls its overridden methods:

class Animal {
public:
virtual void display() { cout << "Animal class" << endl; }
};
class Dog : public Animal {
public:
void display() override { cout << "Dog class" << endl; }
};

34. Virtual and Pure Virtual Methods


Definition:

 Virtual Method: A method in the base class that can be overridden in derived classes.
 Pure Virtual Method: A method with no implementation in the base class, making the
class abstract.

Example: A Shape class with a pure virtual method draw() and a Circle class implementing it:

class Shape {
public:
virtual void draw() = 0; // Pure virtual method
};

35. File Input/Output Using Streams


Definition: File I/O allows reading from and writing to files using ifstream (input file stream)
and ofstream (output file stream).

Example: Writing to and reading from a file:

36. Dynamic Binding


Definition: Dynamic binding (or late binding) allows the method to be called to be determined at
runtime, based on the object type.

Example: A base class pointer invokes the overridden method of the derived class dynamically:

class Animal {
public:
virtual void sound() { cout << "Animal sound" << endl; }
};
class Dog : public Animal {
public:
void sound() override { cout << "Bark" << endl; }
};
Animal* ptr = new Dog();
ptr->sound(); // Output: Bark

37. Operator Overloading


Definition: Operator overloading allows defining custom behavior for operators like +, -, *, etc.,
for user-defined types.

Example: A Complex class overloads the + operator to add two complex numbers:

class Complex {
public:
int real, imag;
Complex operator + (Complex const &obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
};

38. Exception Handling


Definition: Exception handling allows dealing with runtime errors using try, catch, and throw
blocks.

Example: An exception is thrown for division by zero:

try {
if (b == 0) throw "Division by zero!";
cout << a / b << endl;
} catch (const char* msg) {
cout << "Error: " << msg << endl;
}

39. Templates
Definition: Templates allow writing generic functions and classes that can work with any data
type.

Example: A generic add() function works for integers, floats, or other types:

template <typename T>


T add(T a, T b) { return a + b; }
40. Template Specialization
Definition: Template specialization allows providing a specific implementation of a template for
a particular data type.

Example: A specialized Box class handles integers differently:

template <>
class Box<int> {
public:
int getValue() { return value * 10; }
};

41. Virtual Destructor


Definition: A virtual destructor ensures that the destructor of the derived class is called when
deleting an object through a base class pointer.

Example: A base class defines a virtual destructor:

class Base {
public:
virtual ~Base() { cout << "Base destructor" << endl; }
};

42. Construction and Destruction of Objects


Definition: The construction and destruction process ensures proper initialization and cleanup of
objects, especially in inheritance.

Example: A derived class constructor calls the base class constructor, and destruction happens in
reverse order:

class Base {
public:
Base() { cout << "Base constructor" << endl; }
~Base() { cout << "Base destructor" << endl; }
};
class Derived : public Base {
public:
Derived() { cout << "Derived constructor" << endl; }
~Derived() { cout << "Derived destructor" << endl; }
};

43. Aggregation vs Composition


Definition:

 Aggregation: A weak "has-a" relationship where the contained objects can exist independently.
 Composition: A strong "has-a" relationship where the contained objects cannot exist
independently.

Example: A Car class has a composition with Engine (strong relationship) and an aggregation
with Driver (weak relationship):

class Engine {
// Strong relationship
};
class Driver {
// Weak relationship
};

44. File Handling in C++


Definition: File handling in C++ involves reading from and writing to files using standard I/O
library classes such as ifstream and ofstream.

Example: Writing data to a file and reading it back:

ofstream outFile("example.txt");
outFile << "Hello, File!" << endl;
outFile.close();
ifstream inFile("example.txt");

45. Recursion and Inline Functions


Definition: Inline functions are small functions defined with the inline keyword for faster
execution, while recursion refers to functions that call themselves.

Example: An inline function computes the square of a number, and a recursive function
calculates a factorial:

inline int square(int x) { return x * x; }


int factorial(int n) { return (n <= 1) ? 1 : n * factorial(n - 1); }
46. Object Slicing
Definition: Object slicing occurs when a derived class object is assigned to a base class object,
and the derived class-specific data or behavior is lost.

Example: When a Derived object is assigned to a Base object, only the Base portion of the
object is retained:

class Base {
public:
int x;
};
class Derived : public Base {
public:
int y;
};
Base objBase = Derived(); // y is sliced off

47. Multilevel Inheritance


Definition: Multilevel inheritance occurs when a class inherits from a class that is already
derived from another class.

Example: A GrandChild class inherits from Child, which inherits from Parent:

class Parent {
public:
void display() { cout << "Parent class" << endl; }
};
class Child : public Parent {
};
class GrandChild : public Child {
};

48. Multiple Inheritance


Definition: Multiple inheritance allows a class to inherit from more than one base class.

Example: A Child class inherits from both Father and Mother classes:

class Father {
public:
void speak() { cout << "Father speaking" << endl; }
};
class Mother {
public:
void sing() { cout << "Mother singing" << endl; }
};
class Child : public Father, public Mother {
};

49. Diamond Problem


Definition: The diamond problem occurs in multiple inheritance when a derived class inherits
from two classes that have a common base class, causing ambiguity.

Example: The Child class has ambiguity when calling Base methods through Parent1 and
Parent2:

class Base {
public:
void display() { cout << "Base class" << endl; }
};
class Parent1 : public Base {};
class Parent2 : public Base {};
class Child : public Parent1, public Parent2 {};

Solution: Use virtual inheritance to resolve ambiguity.

50. Overriding vs Overloading


Definition:

 Overriding: Redefining a base class method in a derived class.


 Overloading: Defining multiple methods with the same name but different parameters.

Example: Overloading and overriding in a Shape and Circle class:

class Shape {
public:
virtual void draw() { cout << "Drawing Shape" << endl; }
};
class Circle : public Shape {
public:
void draw() override { cout << "Drawing Circle" << endl; }
};
void print(int a);
void print(double b);
51. Shallow Copy
Definition: A shallow copy copies the object's attributes as-is, including pointers, leading to
shared memory between the original and copied objects.

Example: Two objects share the same memory address for a dynamically allocated pointer:

class Box {
public:
int* ptr;
Box(int value) { ptr = new int(value); }
};
Box obj1(10);
Box obj2 = obj1; // Shares the same pointer

52. Deep Copy


Definition: A deep copy creates a new memory allocation for pointers, ensuring the original and
copied objects have independent memory.

Example: A copy constructor performs a deep copy:

class Box {
public:
int* ptr;
Box(int value) { ptr = new int(value); }
Box(const Box& obj) {
ptr = new int(*obj.ptr);
}
};

53. Run-Time Type Information (RTTI)


Definition: RTTI allows determining the type of an object during runtime using operators like
typeid and dynamic_cast.

Example: Using dynamic_cast to safely cast pointers:

Base* basePtr = new Derived();


Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
54. Virtual Table (V-Table)
Definition: A V-Table is a mechanism used by the compiler to support dynamic dispatch of
virtual methods in C++.

Example: The V-Table ensures the correct method is called for a base class pointer:

class Base {
public:
virtual void show() { cout << "Base class" << endl; }
};
class Derived : public Base {
public:
void show() override { cout << "Derived class" << endl; }
};

55. Namespaces
Definition: Namespaces organize code into logical groups and prevent name conflicts in large
projects.

Example: Two classes with the same name are distinguished by their namespace:

namespace First {
class Sample {
public:
void display() { cout << "First namespace" << endl; }
};
}
namespace Second {
class Sample {
public:
void display() { cout << "Second namespace" << endl; }
};
}

You might also like