Object-Oriented Programming

Object-Oriented Programming (OOP) in C++ is a way of organizing your code by modeling it around “objects” that represent real-world things. C++ is a multi-paradigm language that fully supports OOP principles. Below is a detailed breakdown of core OOP concepts in C++, with code examples and explanations:

1. Classes & Objects

Class: A user-defined blueprint for creating objects (encapsulates data and functions).
Object: An instance of a class.

Example:

#include <iostream>
using namespace std;

class Car {
private:
    string brand; // Encapsulated data
    int year;

public:
    // Constructor
    Car(string b, int y) : brand(b), year(y) {}

    // Member function
    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car myCar("Toyota", 2020); // Object creation
    myCar.displayInfo(); // Output: Brand: Toyota, Year: 2020
    return 0;
}

2. Encapsulation

Bundling data (variables) and methods (functions) into a single unit (class) while restricting direct access to some components.

  • Access Specifiers:
    • public: Accessible from anywhere.
    • private: Accessible only within the class (default for class members).
    • protected: Accessible within the class and its derived classes.

Example:

class BankAccount {
private:
    double balance; // Encapsulated data

public:
    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    double getBalance() { return balance; }
};

3. Inheritance

Creating a new class (derived) from an existing class (base) to reuse code.
Types:

  • Single: One base → one derived.
  • Multiple: Multiple bases → one derived (C++ specific).
  • Multilevel: Base → derived → derived.
  • Hierarchical: One base → multiple derived.
  • Hybrid: Combination of multiple types.

Example :

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

class Dog : public Animal { // Dog inherits from Animal
public:
    void bark() { cout << "Barking!" << endl; }
};

int main() {
    Dog myDog;
    myDog.eat(); // Inherited method
    myDog.bark();
}

4. Polymorphism

Ability to perform a single action in different ways.
Types:

  1. Compile-Time Polymorphism:
    • Function Overloading: Multiple functions with the same name but different parameters.
    • Operator Overloading: Defining operators for user-defined types.
  2. Runtime Polymorphism:
    • Virtual Functions: Overriding base class methods in derived classes using virtual keyword.

Example (Virtual Functions):

class Shape {
public:
    virtual void draw() { // Virtual function
        cout << "Drawing a shape." << endl;
    }
};

class Circle : public Shape {
public:
    void draw() override { // Override base method
        cout << "Drawing a circle." << endl;
    }
};

int main() {
    Shape* shape = new Circle();
    shape->draw(); // Output: Drawing a circle. (Dynamic binding)
    delete shape;
}

5. Abstraction

Hiding complex implementation details and exposing only essential features.

  • Achieved using abstract classes (classes with at least one pure virtual function).

Example:

class AbstractCalculator {
public:
    virtual int add(int a, int b) = 0; // Pure virtual function (abstract)
};

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

int main() {
    Calculator calc;
    cout << calc.add(5, 3); // Output: 8
}

6. Constructors & Destructors

  • Constructor: Initializes objects (ClassName()).
  • Destructor: Cleans up resources when objects are destroyed (~ClassName()).

Example:

class Student {
private:
    string name;
public:
    Student(string n) : name(n) { // Constructor
        cout << "Student " << name << " created." << endl;
    }
    ~Student() { // Destructor
        cout << "Student " << name << " destroyed." << endl;
    }
};

int main() {
    Student s("Alice"); // Output: Student Alice created.
    return 0; // Output: Student Alice destroyed.
}

7. Friend Functions & Classes

  • Friend Function: A non-member function with access to private/protected members.
  • Friend Class: A class whose members can access private/protected members of another class.

Example (Friend Function):

class Box {
private:
    int width;
public:
    Box(int w) : width(w) {}
    friend void printWidth(Box b); // Friend function
};

void printWidth(Box b) {
    cout << "Width: " << b.width << endl; // Access private member
}

int main() {
    Box box(10);
    printWidth(box); // Output: Width: 10
}

8. Static Members

  • Static Variable: Shared across all objects of the class.
  • Static Function: Can access only static members.

Example:

class Counter {
public:
    static int count; // Static member
    Counter() { count++; }
    static void showCount() { // Static function
        cout << "Total objects: " << count << endl;
    }
};

int Counter::count = 0; // Initialize static member

int main() {
    Counter c1, c2;
    Counter::showCount(); // Output: Total objects: 2
}

9. The this Pointer

A pointer to the current object instance (used to access members and resolve name conflicts).

Example:

class Person {
private:
    string name;
public:
    void setName(string name) {
        this->name = name; // 'this' resolves variable name conflict
    }
};

Key Features of C++ OOP:

  • Multiple Inheritance: A class can inherit from multiple base classes.
  • Manual Memory Control: Use constructors/destructors for resource management.
  • Operator Overloading: Define custom behavior for operators (e.g., +, <<).

Why C++ OOP Matters:

  • Enables modular, reusable, and maintainable code.
  • Balances high-level abstraction with low-level control.

1 thought on “Object-Oriented Programming”

Leave a Comment