New OOP
New OOP
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:
class Animal {
public:
void eat() { cout << "Eating..." << 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; }
};
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:
class Car {
public:
string brand;
Car(string b) { brand = b; }
};
8. Destructor
Definition
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);
};
Function overloading allows multiple functions with the same name but different parameters.
Example:
Operator overloading allows defining custom behavior for operators like +, -, *, etc., for user-
defined types.
Example:
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;
}
};
Exception handling allows dealing with runtime errors using try, catch, and throw blocks.
Example:
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.
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; }
};
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
};
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:
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:
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
};
A pointer to an object stores the memory address of an object, allowing indirect access to its
members.
Example:
Car myCar;
Car* ptr = &myCar;
ptr->drive();
Dynamic memory allocation allows allocating memory for objects at runtime using new and
releasing it using delete.
Example:
Example:
A Student class defines a copy constructor to copy data from another object.
class Student {
public:
Student(const Student &obj) { name = obj.name; }
};
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; }
};
Streams are used for input/output operations in C++. Examples include cin, cout, and file
streams.
Example:
Example: A function printMessage() with a default value for the message parameter:
int a = 10;
int &ref = a;
ref = 20; // Modifies a
class Box {
private:
int length;
friend class FriendClass;
};
Example: A Counter class uses a static member count to track object creation:
class Counter {
public:
static int count;
Counter() { count++; }
};
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; }
};
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; }
};
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; }
};
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
};
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
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;
}
};
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 <>
class Box<int> {
public:
int getValue() { return value * 10; }
};
class Base {
public:
virtual ~Base() { cout << "Base destructor" << endl; }
};
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; }
};
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
};
ofstream outFile("example.txt");
outFile << "Hello, File!" << endl;
outFile.close();
ifstream inFile("example.txt");
Example: An inline function computes the square of a number, and a recursive function
calculates a factorial:
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
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 {
};
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 {
};
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 {};
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
class Box {
public:
int* ptr;
Box(int value) { ptr = new int(value); }
Box(const Box& obj) {
ptr = new int(*obj.ptr);
}
};
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; }
};
}