Object Oriented Programming in C++.

Object-Oriented Programming (OOP) is a programming paradigm that organizes and structures code around the concept of "objects," which are self-contained units containing both data and behavior. In OOP, objects represent real-world entities, and the programming revolves around interactions between these objects.


The core principles of Object-Oriented Programming are:

  • Encapsulation.
  • Abstraction.
  • Inheritance.
  • Polymorphism.
We are going to cover all these principles in detail with real-life examples in this post but before understanding them there are a few important terms that we need to understand. 

Class

In C++, a class is a user-defined data type that serves as a blueprint for creating objects. It encapsulates data (attributes) and methods (member functions) that operate on that data. Classes enable developers to model real-world entities, organize code, and implement the principles of Object-Oriented Programming (OOP).

Object

In C++, an object is a concrete instance of a class. It is a self-contained unit that combines data (attributes) and behavior (methods) defined in the class blueprint. Objects represent real-world entities and can interact with each other through their methods and attributes.

Let's take a real-world example to understand the concept of class and object and how it works.

Example: Consider we have a class name Vehicle, the Vehicle class contains attributes like Brand, Model, Color, and Fuel Type. It also has some properties like ChangeGear(), GetFuelLevel(), Accelerate(), and Brake(). Using this Vehicle class as a blueprint, we can create multiple vehicle objects, each with its own unique set of attributes and behavior. 

C++ Example Code:
//C++ Example Code to show working of Class and Objects
#include <iostream>
#include <string>
using namespace std;

class Car {
public:
    // Attributes
    string brand;
    string model;
    string color;
    string fuelType;

    // Methods
    void ChangeGear() {
        cout << "The " << brand << " " << model << " is changing Gear...\n";
    }

    void Accelerate() {
        cout << "The " << brand << " " << model << " is accelerating...\n";
    }

    void Brake() {
        cout << "The " << brand << " " << model << " is braking...\n";
    }
};

int main() {
    // Creating car objects using the Car class
    Car car1;

    car1.brand = "Toyota";
    car1.model = "Camry";
    car1.color = "Blue";
    car1.fuelType = "Petrol";

    car1.ChangeGear();
    car1.Accelerate();
    car1.Brake();

    return 0;
}
Output:
The Toyota Camry is changing Gear...
The Toyota Camry is accelerating...
The Toyota Camry is braking...
The memory required to hold the object's data (attributes) and the code for its methods (member functions) is allocated from the computer's memory.(alert-success)

I hope till now you have understood the two most important terms of OOPs that is class and object. Now we are going to explore the core principles of OOPs one by one.


Encapsulation

Encapsulation is the concept of bundling data and methods within a class, hiding internal implementation details from the outside world. It allows for data abstraction and provides access control through public, private, and protected access specifiers. You can read more about Access Specifiers here.


Example: In the Car class, the attributes (make, model, year) may be declared as private, ensuring that they can only be accessed and modified through public methods like getMake() and setMake(). This way, the internal state of the car object is encapsulated and protected.


Example Code:

#include <iostream>
#include <string>
using namespace std;

class Car {
private:
    string make;
    string model;
    int year;

public:
    // Constructor
    Car(string carMake, string carModel, int carYear) {
        make = carMake;
        model = carModel;
        year = carYear;
    }

    // Getter methods
    string getMake() const {
        return make;
    }
    string getModel() const {
        return model;
    }
    int getYear() const {
        return year;
    }

    // Setter methods
    void setMake(string newMake) {
        make = newMake;
    }
    void setModel(string newModel) {
        model = newModel;
    }
    void setYear(int newYear) {
        year = newYear;
    }
};

int main() {
    // Creating a Car object using the constructor
    Car myCar("Toyota", "Camry", 2022);

    // Using the setter methods to modify attributes
    myCar.setMake("Honda");
    myCar.setModel("Civic");
    myCar.setYear(2021);

    // Displaying the updated car details
    cout << "\nUpdated Car Details:" << endl;
    cout << "Make: " << myCar.getMake() << endl;
    cout << "Model: " << myCar.getModel() << endl;
    cout << "Year: " << myCar.getYear() << endl;

    return 0;
}
Output:
Updated Car Details:
Make: Honda
Model: Civic
Year: 2021

Access specifiers are keywords used in class definitions to control the visibility and accessibility of class members (attributes and methods) from outside the class. (alert-success) 


Abstraction

Abstraction involves representing essential features and behavior of objects while hiding unnecessary details. It allows us to focus on what an object does rather than how it does it.

Abstraction is achieved in C++ through the use of classes and access specifiers (public, private, protected). The public interface of the class represents the abstraction, while the private and protected sections hide the implementation details from external code. 

Example: In a banking application, a BankAccount class may provide methods like deposit(), withdraw(), and getBalance(), abstracting away the complex internal banking operations and exposing only the essential functionality needed by users.


Inheritance

Inheritance is a mechanism that allows a class to inherit properties and behaviors from another class, forming a hierarchical relationship. The derived class (child class) inherits the characteristics of the base class (parent class).
Inheritance allows for code reuse, as the derived class can reuse the properties and behaviors of the base class, eliminating the need to rewrite common code.(alert-success)

They are classified into various types based on the hierarchy and relationships between classes and these are:

  • Single Inheritance: A derived class inherits from only one base class. 
  • Multiple Inheritance: A derived class can inherit from two or more base classes.
  • Multilevel Inheritance: A derived class inherits from another derived class, creating a chain of inheritance.
  • Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
  • Hybrid (or Virtual) Inheritance: A combination of multiple and multilevel inheritance.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables the same method to be implemented in different ways in different classes, based on their specific behavior.

Example: Using the vehicle hierarchy, a generic method like drive() can be defined in the base class Vehicle. Each derived class (Car, Motorcycle, Truck) can provide its own implementation of the drive() method based on the unique way each vehicle type operates.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS