C++ Object-Oriented Programming (OOP)

Welcome to The Coding College! In this tutorial, we’ll explore the core concepts of Object-Oriented Programming (OOP) in C++. OOP is a programming paradigm that revolves around the concept of objects—real-world entities represented in code.

What is Object-Oriented Programming?

OOP in C++ is a way to design and write code by encapsulating data and functions into objects. It makes programs more modular, reusable, and easier to maintain.

Key Concepts of OOP

  1. Classes and Objects
  2. Encapsulation
  3. Abstraction
  4. Inheritance
  5. Polymorphism

Let’s break down these concepts step-by-step.

1. Classes and Objects

Class:

A class is a blueprint for creating objects. It defines the properties (data members) and behaviors (member functions) of an object.

Object:

An object is an instance of a class, representing a specific entity.

Example:

#include <iostream>
using namespace std;

// Define a class
class Car {
public:
    string brand; // Attribute
    int year;     // Attribute

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

int main() {
    Car car1;            // Create an object of Car
    car1.brand = "Tesla"; // Assign values
    car1.year = 2023;

    car1.displayInfo();   // Call the method
    return 0;
}

Output:

Brand: Tesla, Year: 2023  

2. Encapsulation

Encapsulation is the bundling of data and functions that manipulate the data. It restricts direct access to some components using access specifiers:

  • Public: Accessible from anywhere.
  • Private: Accessible only within the class.
  • Protected: Accessible within the class and derived classes.

Example:

#include <iostream>
using namespace std;

class Person {
private:
    string name; // Private data member

public:
    // Setter method
    void setName(string n) {
        name = n;
    }

    // Getter method
    string getName() {
        return name;
    }
};

int main() {
    Person person1;
    person1.setName("John Doe");
    cout << "Name: " << person1.getName() << endl;
    return 0;
}

Output:

Name: John Doe  

3. Abstraction

Abstraction hides unnecessary details and shows only essential features. In C++, this is often achieved using classes and abstract classes (classes with at least one pure virtual function).

Example:

#include <iostream>
using namespace std;

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

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing a Circle" << endl;
    }
};

int main() {
    Circle c1;
    c1.draw();
    return 0;
}

Output:

Drawing a Circle  

4. Inheritance

Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class).

Example:

#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "This animal eats food." << endl;
    }
};

class Dog : public Animal {
public:
    void bark() {
        cout << "The dog barks." << endl;
    }
};

int main() {
    Dog dog1;
    dog1.eat();  // Inherited method
    dog1.bark(); // Method of Dog class
    return 0;
}

Output:

This animal eats food.  
The dog barks.  

5. Polymorphism

Polymorphism allows functions or methods to behave differently based on the object they are acting upon. C++ supports two types:

  1. Compile-Time Polymorphism (Function Overloading, Operator Overloading)
  2. Run-Time Polymorphism (Function Overriding with Virtual Functions)

Example: Function Overloading

#include <iostream>
using namespace std;

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

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

int main() {
    Math math;
    cout << "Sum (int): " << math.add(5, 10) << endl;
    cout << "Sum (double): " << math.add(3.5, 4.5) << endl;
    return 0;
}

Output:

Sum (int): 15  
Sum (double): 8  

Example: Function Overriding with Virtual Functions

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() {
        cout << "This animal makes a sound." << endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        cout << "The dog barks." << endl;
    }
};

int main() {
    Animal* animalPtr;
    Dog dog1;
    animalPtr = &dog1;

    animalPtr->sound(); // Calls the Dog's sound method
    return 0;
}

Output:

The dog barks.  

Advantages of OOP

  1. Modularity: Code is easier to manage and debug.
  2. Reusability: Inheritance allows code reuse across different classes.
  3. Scalability: Easier to scale programs with well-defined objects.
  4. Real-World Representation: Models real-world entities effectively.

Practical Example: OOP in a Banking System

#include <iostream>
using namespace std;

class BankAccount {
private:
    string accountHolder;
    double balance;

public:
    BankAccount(string name, double initialBalance) {
        accountHolder = name;
        balance = initialBalance;
    }

    void deposit(double amount) {
        balance += amount;
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        } else {
            cout << "Insufficient balance!" << endl;
        }
    }

    void displayAccount() {
        cout << "Account Holder: " << accountHolder << ", Balance: $" << balance << endl;
    }
};

int main() {
    BankAccount account1("John Doe", 500.00);
    account1.displayAccount();

    account1.deposit(200.00);
    account1.displayAccount();

    account1.withdraw(100.00);
    account1.displayAccount();

    account1.withdraw(700.00); // Insufficient balance
    return 0;
}

Output:

Account Holder: John Doe, Balance: $500  
Account Holder: John Doe, Balance: $700  
Account Holder: John Doe, Balance: $600  
Insufficient balance!  

Explore More at The Coding College

To master OOP concepts and learn how to apply them in advanced C++ projects, visit The Coding College.

Leave a Comment