Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Object Oriented Programming (OOPs) Concepts in C++

Object Oriented Programming (OOPs) Concepts in C++

22 Nov 2024
Advanced
30K Views
29 min read
Learn with an interactive course and practical hands-on labs

Free C++ Course: Learn C++ In 21 Days

OOPs Concepts in C++

OOP concepts make C++ programming efficient and more managed. Consider creating a game, Instead of managing everything manually, you may define "classes" such as Player, Enemy, and PowerUp, each having their own set of properties and actions. Doesn't that sound cool?

Hence In this C++ tutorial, we are going to look at object-oriented programming in cpp concepts in depth. In this approach, the whole world is looked at from the spectacles of objects. Numerous items we come into contact with every day, such as phones & cars, are all objects.

What is Object-Oriented Programming (OOPs) in C++?

It is a programming paradigm in which everything is represented as an object. OOPs, implement real-world entities in the form of objects. The main aim of OOP is to organize together the data and the functions that operate on them so that no other part of the program can access this data except that function.

Basic OOP Concepts in C++

The concept of OOPs in C++ programming language is based on eight major pillars which are

  1. Class
  2. Object
  3. Inheritance
  4. Polymorphism
  5. Abstraction
  6. Encapsulation
  7. Dynamic Binding
  8. Message Passing

Object-Oriented Programming (OOP) Concepts in C++

1.) Class

A class in C++ is one of the fundamental concepts in Object-Oriented Programming (OOP). It acts as a blueprint or a template for creating objects, which represent real-world entities. A class encapsulates data members (attributes) and member functions (methods) that operate on the data, providing a way to model complex systems.

 Class in OOPs

Key Characteristics of a Class

  • Encapsulation: A class bundles data (attributes) and functions (methods) together, restricting direct access to some of the object's components and maintaining data integrity.
  • Reusability: Once a class is defined, it can be reused to create multiple objects, reducing redundancy and enhancing modularity.
  • Abstraction: Classes allow you to hide the implementation details and expose only the necessary features through public methods.
  • Inheritance: Classes can inherit attributes and methods from other classes, enabling code reuse and hierarchical relationships.
  • Polymorphism: A class can define methods that are overridden in derived classes, allowing for dynamic behavior.

Structure of a Class in C++

A class typically has:

  1. Data Members: Variables that hold the state of the class.
  2. Member Functions: Functions that define the behavior of the class.
  3. Access Specifiers: Keywords (public, private, protected) to control the accessibility of data members and methods.

Syntax

class ClassName {
private:
    // Private data members and methods (only accessible within the class)

public:
    // Public data members and methods (accessible outside the class)
    
    // Constructor: Initializes class objects
    ClassName() {
        // Initialization code
    }

    // Destructor: Cleans up resources
    ~ClassName() {
        // Cleanup code
    }
};

Example: Creating and Using a Class in C++


#include <iostream>
using namespace std;

// Class definition
class Car {
private:
    string brand;
    int speed;

public:
    // Constructor
    Car(string carBrand, int carSpeed) {
        brand = carBrand;
        speed = carSpeed;
    }

    // Method to display car details
    void display() {
        cout << "Car Brand: " << brand << ", Speed: " << speed << " km/h" << endl;
    }

    // Method to update speed
    void updateSpeed(int newSpeed) {
        speed = newSpeed;
        cout << "Speed updated to " << speed << " km/h" << endl;
    }
};

int main() {
    // Creating objects of the Car class
    Car car1("Toyota", 120);
    Car car2("Honda", 140);

    // Accessing methods of the Car class
    car1.display();
    car2.display();

    car1.updateSpeed(150);
    car1.display();

    return 0;
}
    

Output


Car Brand: Toyota, Speed: 120 km/h
Car Brand: Honda, Speed: 140 km/h
Speed updated to 150 km/h
Car Brand: Toyota, Speed: 150 km/h
   

Key Features in the Example

  • Encapsulation: The brand and speed variables are private and can only be accessed or modified through public methods.
  • Reusability: The Car class is used to create multiple objects (car1 and car2).
  • Data Protection: Direct access to the brand and speed attributes is restricted, preventing accidental modifications.

Real-Life Analogy

A class is like a blueprint for a car. The blueprint defines the attributes (e.g., color, speed, brand) and behaviors (e.g., accelerate, brake). Once you have the blueprint, you can create multiple cars (objects) from it, each with unique attributes but sharing the same structure and functionality.

2.) Object

An Object in Oop is a real-world entity that has a particular behavior and a state. It can be physical or logical in C++ programming language. An object is an instance of a class and memory is allocated only when an object of the class is created.

Object in OOPs

Example illustrating Classes and Objects in C++ Compiler


#include <iostream>
#include <string>

class MyClass {    // The class
public:             // Access specifier
    int num;      // Attribute (int variable)
    std::string string;  // Attribute (string variable)
};

int main() {
    MyClass obj;  // Create an object of MyClass

    // Access attributes and set values
    obj.num = 25; 
    obj.string = "Welcome to ScholarHat";

    // Print attribute values
    std::cout << obj.num << "\n";
    std::cout << obj.string;

    return 0;
}
    

Output

25
Welcome to ScholarHat  

3.) Inheritance

It is the phenomenon when a class derives its characteristics from another class. In other words, when an object of a class derives all its properties from the parent object. The class that inherits the properties is known as the child class/derived class and the main class is called the parent class/base class.

 Inheritance in OOPs

Example illustrating Inheritance in C++


#include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; 
        height=b;
      }
 };

class Rectangle: public Polygon {
  public:
    int area ()
      { return width * height; }
 };

class Triangle: public Polygon {
  public:
    int area ()
      { return width * height / 2; }
  };
  
int main () {
  Rectangle rect;
  Triangle trgl;
  rect.set_values (7,5);
  trgl.set_values (9,7);
  cout << rect.area() << '\n';
  cout << trgl.area() << '\n';
  return 0;
}
 

Output

35
31

To get into the details of Inheritance, refer to Inheritance in C++ with Modifiers

4.) Polymorphism

Polymorphism means the ability to take more than one form in the C++ programming language. With this feature, you can use the same function to perform different tasks thus increasing code reusability.

 Polymorphism

Example illustrating Polymorphism in C++ Online Editor


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

// Base class
class MangoTree {
  public:
    void respire() {
      cout << "The mango trees do respiration at night. \n";
    }
};

// Derived class
class NeemTree : public MangoTree {
  public:
    void respire() {
      cout << "Respiration in neem trees occurs mainly through stomata. \n";
    }
};

int main() {
  MangoTree myMangoTree;
  NeemTree myNeemTree;

  myMangoTree.respire();
  myNeemTree.respire();
  return 0;
}

Output

The mango trees do respiration at night. 
Respiration in neem trees occurs mainly through stomata. 

To get into the details of Polymorphism, refer to Polymorphism in C++: Types of Polymorphism.

5.) Abstraction

Abstraction in C++ programming language helps in the process of data hiding. It assists the program in showing the essential features without showing the functionality or the details of the program to its users. It generally avoids unwanted information or irrelevant details but shows the important part of the program.

Example illustrating Abstraction in C++

#include <iostream>
using namespace std;
class TestAbstraction {
    private: string x, y;

    public:
        void set(string a, string b) {
            x = a;
            y = b;
        }
        
    //printing values  
    void print() {
        cout << "x = " << x << endl;
        cout << "y = " << y << endl;
    }
};

int main() {
    TestAbstraction t1;
    t1.set("ScholarHat", "DotNetTricks");
    t1.print();

    return 0;
}
 

Output

x = ScholarHat
y = DotNetTricks

To get into the details of Abstraction, refer to Interfaces and Data Abstraction in C++.

6.) Encapsulation

Encapsulation helps to wrap up the functions and data together in a single unit. By privatizing the scope of the data members it can be achieved. This particular feature makes the program inaccessible to the outside world.

Encapsulation

Example illustrating Encapsulation in C++

class MyClass {    // The class
public:             // Access specifier
    int num;      // Attribute (int variable)
    std::string string;  // Attribute (string variable)

   // class function
    void show_data() {
        // code
};    

In the above example in C++ Editor, we bundled together the variables num, string, and the function show_data() into a class named MyClass. Encapsulation ensures that only member functions of a class can access its data, which results in data hiding.

In C++, we hide data using private and protected keywords. In contrast, using the public keyword for certain class members makes those members accessible to all other functions and classes.

7) Dynamic Binding

Dynamic binding, also known as late binding, is a key concept in Object-Oriented Programming in C++. It refers to the process of linking a function call to its corresponding function at runtime rather than at compile time. This is primarily used with virtual functions and enables polymorphism, allowing for more flexible and dynamic code.

In dynamic binding in C++, the code to be executed in response to the function call is decided at runtime. C++ has a feature of virtual functions to support this.

 Dynamic Binding in OOPs

How Dynamic Binding Works

  1. Virtual Functions: A member function in a base class is declared as virtual when you want derived classes to override it. This signals the compiler to use dynamic binding for this function.
  2. Virtual Table (vtable): The compiler creates a table called the vtable, which stores function pointers for the virtual functions of a class. Each object has a hidden pointer (vptr) to the appropriate vtable.
  3. Runtime Decision: When a virtual function is called using a base class pointer or reference pointing to a derived class object, the program determines which function to execute based on the actual type of the object at runtime.

Code Example


#include <iostream>
using namespace std;

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

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

int main() {
    Base* basePtr;
    Derived derivedObj;

    basePtr = &derivedObj;

    // Dynamic binding happens here
    basePtr->show();

    return 0;
}
    

Output

 Derived class function

Key Points

  • The function call basePtr->show() is resolved at runtime, as show() is declared as a virtual function.
  • Without the virtual keyword, the base class function (Base::show()) would be executed, as the function call would be resolved at compile time (known as static binding).

Benefits of Dynamic Binding

  • Flexibility: Makes code more adaptable to changes.
  • Polymorphism: Allows for defining one interface and implementing it differently in derived classes.
  • Reusability: Encourages using base class references/pointers for a variety of derived types.

8.) Message Passing

Objects communicate with one another by sending and receiving information from each other. Message passing involves specifying the name of the object, the name of the function, and the information to be sent.

Message Passing in OOPs

Read More - C++ Interview Questions Interview Questions for Freshers

Message passing is a core concept in Object-Oriented Programming (OOP) that allows objects to communicate with one another. In C++, message passing involves invoking methods (functions) of an object using another object or instance. This mechanism helps in achieving encapsulation and abstraction, making programs modular and easier to maintain.

Key Characteristics of Message Passing in C++

  • Object Interaction: Objects send and receive messages by calling member functions defined in their respective classes.
  • Encapsulation: The internal state of an object is accessed and modified only through its public methods, ensuring data safety.
  • Polymorphism and Overriding: Dynamic behavior can be achieved when derived class objects respond to a message differently using overridden methods.
  • Parameters as Messages: Data can also be passed as parameters to the member functions, acting as the content of the "message."

Example of Message Passing in C++

#include <iostream>
using namespace std;

// Class definition
class BankAccount {
private:
    string accountHolder;
    double balance;

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

    // Method to deposit money
    void deposit(double amount) {
        balance += amount;
        cout << "Deposited: " << amount << ". New Balance: " << balance << endl;
    }

    // Method to withdraw money
    void withdraw(double amount) {
        if (amount > balance) {
            cout << "Insufficient funds!" << endl;
        } else {
            balance -= amount;
            cout << "Withdrew: " << amount << ". New Balance: " << balance << endl;
        }
    }

    // Method to display account details
    void display() {
        cout << "Account Holder: " << accountHolder << ", Balance: " << balance << endl;
    }
};

int main() {
    // Create an object of BankAccount
    BankAccount account("Alice", 1000.0);

    // Sending messages to the object
    account.display();          // Message: display()
    account.deposit(500.0);     // Message: deposit()
    account.withdraw(200.0);    // Message: withdraw()

    return 0;
}
    

Output

Account Holder: Alice, Balance: 1000 
Deposited: 500. New Balance: 1500
Withdrew: 200. New Balance: 1300

How Message Passing Works

  1. Object Creation: The accountthe object is created using the BankAccount class.
  2. Calling Methods: Messages are passed by invoking the methods deposit, withdraw, and display on the account object.
  3. Processing Messages: The class processes these messages using its member functions, updating or accessing the private data.

Benefits of Message Passing

  • Encapsulation:The internal state is protected, and accessed only through methods.
  • Modularity: Functions handle specific tasks, making the code easier to debug and extend.
  • Flexibility: Promotes object interaction and supports polymorphism in complex systems.

Real-Life Analogy

Imagine a bank account object as a customer at the bank. The customer sends "messages" (like deposit or withdrawal requests) to the bank, and the bank processes these requests to update the account balance. This is how message passing enables interaction between different entities in a system.

Advantages of OOP in C++

  • The OOP provides reusability to the code and extends the usage of the existing classes.
  • Object-oriented programming makes it easy to maintain any particular code as there are objects and classes. There is no need to restructure the code.
  • This particular feature in the C++ programming language also helps in data-hiding methods. It is very helpful to keep the data and information safe from getting exposed to leaking.
  • Object-oriented programming provides the ability to simulate real-world events much more effectively.

Disadvantages of OOP in C++

  • As OOP programs are large, they need more time to run, resulting in slower execution.
  • OOP is not a universal language, so we can only use it in some places. It is only used when necessary. It is not appropriate for all sorts of issues.
  • Everything is represented as an object in OOP, so before applying it, we need to think about objects well.

Procedural Programming vs. Object-Oriented Programming

Procedure Oriented Programming Object Oriented programming
the program is divided into small parts called functions.the program is divided into small parts called objects.
It follows a top-down approach.It follows a bottom-up approach.
There is no access specifierIt has access specifiers like private, public, protected, etc.
The addition of new data and functions is not easy.The addition of new data and functions is easy.
No proper way of hiding data so it is less secure.Object-oriented programming provides data hiding so it is more secure.
overloading is not possible.Overloading is possible
there is no concept of data hiding and inheritance.The concept of data hiding and inheritance is used.
the function is more important than the data.data is more important than function.
It is used for designing medium-sized programs.It is used for designing large and complex programs.
Code reusability is absent in procedural programming,Code reusability is present in object-oriented programming.
Summary

This article has made you familiar with OOP in C++ Programming. Understanding how to work with objects and classes is essential for any programmer, and that’s why exploring a C++ certification course would be beneficial for those who want to be able to master this powerful language. Thanks for reading! We hope you have a better understanding of OOP concepts and object classes in C++ now.

FAQs

Classes do not use memory. They merely serve as a template from which items are made. Now, objects initialize the class members and methods when they are created, using memory in the process.

No. If the base class includes non-static methods, an object must be constructed. But no objects need to be generated if the class includes static methods.

Abstraction is similar to data encapsulation. It means showing only the necessary information and hiding the other irrelevant information from the user.

It is widely used in many popular programming languages such as:
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this