Object Oriented Programming (OOPs) Concepts in C++

Object Oriented Programming (OOPs) Concepts in C++

21 May 2024
Advanced
17.4K Views
17 min read
Learn via Video Course & by Doing Hands-on Labs

C++ Programming For Beginners

OOPs Concepts in C++: An Overview

In this C++ tutorial, we are going to look at a very important concept in C++ programming i.e. object-oriented programming. 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. In this blog post, we'll dive deeper into the OOP concepts in C++ and look atits implementation in C++ programming. For practicals and in-depth understanding, enroll in our C++ training section.

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

Class is a collection of objects. It is like a blueprint for an object. In the C++ programming language, a class is the foundational element of object-oriented programming. An instance of a class is created for accessing its data types and member functions.

 Class in OOPs

2.) Object

An object 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

In dynamic binding, 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

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

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

Q1. How much memory does a class occupy?

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.

Q2. Is it always necessary to create objects from class?

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.

Q3. What is Abstraction?

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

Q4. What are some commonly used Object Oriented Programming Languages?

It is widely used in many popular programming languages such as:
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Angular Certification Course Jun 16 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core Certification Training Jun 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
.NET Microservices Certification Training Jun 23 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core (Project) Jun 23 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Azure Developer Certification Training Jun 23 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Generative AI For Software Developers Jul 14 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this