All About OOPs Concepts in C++

All About OOPs Concepts in C++

16 mins read9.2K Views Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Oct 13, 2024 21:29 IST

Have you ever wondered how complex software systems are so efficiently organized and managed? This is where the principles of Object-Oriented Programming (OOP) in C++ come into play. OOP in C++ helps structure code in a way that models real-world entities, making software development more intuitive, flexible, and maintainable. Let's understand more!

OOPs stands for Object Oriented Programming System. It is centred around objects, which are instances of classes. A class acts as a blueprint for creating objects and defines their properties (attributes) and behaviours (methods). The main principles of OOP include Encapsulation, Inheritance, Polymorphism, and Abstraction. Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to organize software design.

Recommended online courses

Best-suited C++ courses for you

Learn C++ with these high-rated online courses

– / –
4 months
4.24 K
6 weeks
– / –
15 days
– / –
– / –
– / –
2 hours
Free
9 hours
Free
3 hours
Free
4 hours

Understanding OOPs Concepts in Java
Understanding OOPs Concepts in Java
Object oriented programming (OOP) concepts are the fundamental pillars of programming. The article below explains the OOPs concept in Java. It covers introductions to OOPs, class, objects, inheritance, abstraction, encapsulation,...read more

Table of Content

 

Why Do We Need OOP?

OOP addresses several issues prevalent in procedural programming paradigms.

  • OOP allows for code reusability through inheritance, making it easier to maintain and modify existing code.
  • With OOP, a program can be divided into smaller, manageable parts (objects), reducing complexity and improving modularity.
  • OOP's approach to modelling real-world entities makes it easier to understand and design complex systems.
  • The use of polymorphism and abstraction provides flexibility in code, facilitating scalability for growing applications.

In this blog, we'll simplify OOP by comparing it to a library system, a context familiar to most of us. Imagine a library with its books, categorization methods, and management systems. We'll use this analogy to explain complex OOP concepts like classes, objects, encapsulation, abstraction, inheritance, and polymorphism. This approach aims to make OOP more approachable and understandable, especially for those who might find it otherwise technically challenging. By the end of this, you'll have a clear understanding of these key OOP principles, seeing how they align with the everyday workings of a library.

Flowchart Illustrating All Key Concepts Both Technically and in Form of the Analogy

1. Technically

2. Using the above analogy

 

Let's see all the OOPs concepts in C++ one by one in detail below by taking the analogy described above into consideration.

1. Class and Object

Analogy: Think of a class as a blueprint for a book, defining properties like title and author, and behaviours like reading. An object is a specific book instance created from this blueprint.

Technical Explanation: A class in C++ is a template for creating objects, encapsulating data and functions. Objects are instances of this class, each having its own values for the class's properties.

C++ Code & Explanation


 
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
string title; // Property
string author; // Property
void read() { // Method
cout << "Reading " + title << endl;
}
};
int main() {
Book myBook; // Creating an object
myBook.title = "C++ Fundamentals"; // Assigning value to property
myBook.read(); // Invoking method
return 0;
}
Copy code

Output

Reading C++ Fundamentals

This code defines a Book class with two properties (title and author) and a method (read). An object myBook is created from the Book class, and its title property is set. When myBook.read() is called, it outputs "Reading C++ Fundamentals".

2. Encapsulation

Analogy: Encapsulation in a library system is like having the book details securely stored. These details are accessed and modified only through specific library methods like check-in or check-out.

Technical Explanation: Encapsulation in C++ involves bundling data (variables) and methods that operate on the data within one unit (class) and restricting direct access to some of the object's components.

C++ Code & Explanation


 
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title; // Encapsulated property
public:
// Setter method
void setTitle(string t) {
title = t;
}
// Getter method
string getTitle() {
return title;
}
};
int main() {
Book book;
book.setTitle("C++ Encapsulation"); // Setting value securely
cout << book.getTitle() << endl; // Accessing value securely
return 0;
}
Copy code

Output

C++ Encapsulation

This code demonstrates encapsulation by making the title property private. It can only be accessed and modified via public methods setTitle and getTitle. When book.getTitle() is called after setting the title, it returns the title of the book.

3. Abstraction

Analogy: Abstraction is like the library catalog, providing necessary information (like book titles and locations) without revealing the complex background management of the books.

Technical Explanation: Abstraction in C++ means exposing only necessary and relevant parts of the class to the user, hiding the complex implementation details.

C++ Code & Explanation


 
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
void findBook() { // User-friendly method
checkDatabase(); // Hidden from user
displayLocation(); // Display relevant info
}
private:
void checkDatabase() {
// Complex background process
}
void displayLocation() {
cout << "Book location displayed" << endl;
}
};
int main() {
Book book;
book.findBook(); // Simplified interface for user
return 0;
}
Copy code

Output

Book location displayed

This code exemplifies abstraction. The findBook method provides a simplified interface to the user. The complex processes like checkDatabase are hidden. When book.findBook() is called, it only shows the user-friendly output, hiding the complexity of checkDatabase.

4. Inheritance

Analogy: Different book genres like "Fiction" inherit basic characteristics of a general "Book" class but also have additional attributes unique to them.

Technical Explanation: Inheritance in C++ allows creating a new class (subclass) based on an existing class (superclass), inheriting its properties and methods, and possibly adding new ones.

C++ Code & Explanation


 
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
string title; // Common attribute
};
class Fiction : public Book { // Inheriting from Book
public:
string genre = "Fiction"; // Additional attribute
};
int main() {
Fiction myFiction;
myFiction.title = "The Alchemist"; // Inherited attribute
return 0;
}
Copy code

Output

The code doesn't produce an output by itself but demonstrates how inheritance works.

Here, Fiction is a subclass that inherits from the Book class. It inherits the title property and adds a new property genre. When a Fiction object is created, and its title is set, it has both the inherited property and its unique property.

5. Polymorphism

Analogy: Polymorphism is like categorizing books in multiple ways. The same book can be categorized by title, author, or genre, demonstrating different behaviors under a common interface.

Technical Explanation: Polymorphism in C++ allows objects to take many forms, particularly enabling a method to perform different tasks based on the object it is called upon.

C++ Code & Explanation


 
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
virtual void categorize() {
cout << "Categorizing by title" << endl;
}
};
class Fiction : public Book {
public:
void categorize() override {
cout << "Categorizing by genre" << endl;
}
};
int main() {
Book* book1 = new Book();
Book* book2 = new Fiction();
book1->categorize(); // Categorizing by title
book2->categorize(); // Categorizing by genre (overridden method)
// Clean up to prevent memory leak
delete book1;
delete book2;
return 0;
}
Copy code

Output

Categorizing by title
Categorizing by genre

This code demonstrates polymorphism. The categorize method in the base class Book is overridden in the subclass Fiction. Depending on the type of object (Book or Fiction), categorize behaves differently.

Examples Showing Usage of OOPs Concept in C++

Example 1: Vehicle Management System

Problem Statement: Develop a system to manage different types of vehicles (like cars, trucks, and motorcycles) in a garage, where each vehicle type has specific attributes and behaviours.


 
#include <iostream>
#include <string>
using namespace std;
// Base class Vehicle
class Vehicle {
protected:
string make;
string model;
public:
Vehicle(string m, string mod) : make(m), model(mod) {}
virtual void display() = 0; // Pure virtual function
};
// Derived class Car
class Car : public Vehicle {
public:
Car(string m, string mod) : Vehicle(m, mod) {}
void display() override {
cout << "Car: " << make << " " << model << endl;
}
};
// Derived class Truck
class Truck : public Vehicle {
public:
Truck(string m, string mod) : Vehicle(m, mod) {}
void display() override {
cout << "Truck: " << make << " " << model << endl;
}
};
// Derived class Motorcycle
class Motorcycle : public Vehicle {
public:
Motorcycle(string m, string mod) : Vehicle(m, mod) {}
void display() override {
cout << "Motorcycle: " << make << " " << model << endl;
}
};
int main() {
Vehicle* v1 = new Car("Toyota", "Corolla");
Vehicle* v2 = new Truck("Ford", "F-150");
Vehicle* v3 = new Motorcycle("Harley-Davidson", "Street 750");
v1->display();
v2->display();
v3->display();
delete v1;
delete v2;
delete v3;
return 0;
}
Copy code

Output

Car: Toyota Corolla
Truck: Ford F-150
Motorcycle: Harley-Davidson Street 750

Here,

  • This code uses inheritance, where Car, Truck, and Motorcycle are derived from the base class Vehicle.
  • Each derived class overrides the display method, showcasing polymorphism.
  • The concept of encapsulation is employed to protect vehicle data (make and model).
  • This design allows for extending the vehicle types easily, adhering to OOP principles.

Example 2: Online Book Store

Problem Statement: Create a system for an online bookstore that manages different genres of books, each with unique attributes and shared characteristics.


 
#include <iostream>
#include <string>
using namespace std;
// Base class Book
class Book {
protected:
string title;
float price;
public:
Book(string t, float p) : title(t), price(p) {}
virtual void display() = 0; // Pure virtual function
};
// Derived class Fiction
class Fiction : public Book {
public:
Fiction(string t, float p) : Book(t, p) {}
void display() override {
cout << "Fiction: " << title << ", Price: $" << price << endl;
}
};
// Derived class NonFiction
class NonFiction : public Book {
public:
NonFiction(string t, float p) : Book(t, p) {}
void display() override {
cout << "Non-Fiction: " << title << ", Price: $" << price << endl;
}
};
int main() {
Book* b1 = new Fiction("1984", 8.99);
Book* b2 = new NonFiction("Sapiens", 12.99);
b1->display();
b2->display();
delete b1;
delete b2;
return 0;
}
Copy code

Output

Fiction: 1984, Price: $8.99
Non-Fiction: Sapiens, Price: $12.99

Here,

  • The Book class is a base class for different book genres like Fiction and NonFiction.
  • Each derived class has a unique display method, demonstrating polymorphism.
  • The title and price properties are encapsulated within the Book class.
  • This setup allows for the easy addition of new book genres, showcasing the scalability of OOP.

Example 3: Employee Management System

Problem Statement: Implement a system to manage employees in a company, categorizing them into different departments like Engineering, Sales, and HR, each with specific roles and common attributes.


 
#include <iostream>
#include <string>
using namespace std;
// Base class Employee
class Employee {
protected:
string name;
int id;
public:
Employee(string n, int i) : name(n), id(i) {}
virtual void role() = 0; // Pure virtual function
};
// Derived class Engineer
class Engineer : public Employee {
public:
Engineer(string n, int i) : Employee(n, i) {}
void role() override {
cout << "Engineer: " << name << ", ID: " << id << endl;
}
};
// Derived class SalesPerson
class SalesPerson : public Employee {
public:
SalesPerson(string n, int i) : Employee(n, i) {}
void role() override {
cout << "Sales Person: " << name << ", ID: " << id << endl;
}
};
int main() {
Employee* e1 = new Engineer("Alice", 101);
Employee* e2 = new SalesPerson("Bob", 102);
e1->role();
e2->role();
delete e1;
delete e2;
return 0;
}
Copy code

Output

Engineer: Alice, ID: 101
Sales Person: Bob, ID: 102

Here,

  • Employee is the base class with common attributes like name and id.
  • The Engineer and SalesPerson classes inherit from Employee and implement the role method, showing polymorphism.
  • Employee data is encapsulated, with access controlled through constructors and methods.
  • This structure allows for easy integration of new employee types, demonstrating the flexibility of OOP.

Table Summarizing All the Key Concepts of OOPs

Here's a table that summarizes all that we learned above for a quick glance for our readers.

OOP Concept

Properties/Characteristics

Technical Definition

Analogy Example

Uses/Relevance

Class

Blueprint, Template

A user-defined data type that encapsulates attributes and methods.

Blueprint of a building.

Defines the structure and behaviour of objects. Used as a template to create objects.

Object

Instance of a class

An instance of a class containing real values, not just the layout.

A specific building constructed from a blueprint.

Represents real-world entities. Each object is an instance of a class.

Encapsulation

Data hiding, Access control

Bundling of data and methods that manipulate the data within one unit and hiding them from external access.

A capsule; only the necessary information is exposed, rest is hidden inside.

Protects the internal state of an object. Prevents unauthorized access and modification.

Abstraction

Simplification, Hiding complexity

The concept of hiding the complex reality while exposing only the necessary parts.

Car's dashboard; hides the complex engine details and only shows what the driver needs to see.

Reduces complexity and isolates impact of changes.

Inheritance

Hierarchical relationships

A mechanism where a new class is derived from an existing class.

Genetic inheritance in biology. Children inherit traits from parents.

Promotes code reuse. Establishes a relationship between new and existing classes.

Polymorphism

Multiple forms, Dynamic method invocation

The ability of different classes to provide a unique implementation of a method, even if they share the same interface.

A person behaving differently in different contexts (teacher, parent, friend).

Allows objects of different classes to be treated as objects of a common superclass. Enhances flexibility and scalability.

Why is C++ a Partial OOP?

C++ is often described as a "partial" or "semi" Object-Oriented Programming (OOP) language because, while it supports key OOP concepts like classes, objects, inheritance, polymorphism, and encapsulation, it also retains many features of procedural programming languages. This combination of OOP and procedural programming characteristics results in C++ being a multi-paradigm language rather than a purely OOP language. 

Top OOPs Interview Questions and Answers (2023)
Top OOPs Interview Questions and Answers (2023)
Object-oriented programming (OOP) is a paradigm that uses objects containing data in programming. It has become a fundamental part of software development. Many companies hire professionals who have a good...read more

Difference Between Constructor and Destructor
Difference Between Constructor and Destructor
Have you ever wondered about the distinguishing roles of constructors and destructors in programming? Constructors initialize new objects, setting up initial states and allocating resources, while destructors clean up, releasing...read more

Difference Between Method Overloading And Method Overriding - Simplified
Difference Between Method Overloading And Method Overriding - Simplified
Programming involves many ideas like polymorphism, inheritance, data abstraction, and handling exceptions. Polymorphism, which includes ideas like method overloading and method overriding, is especially interesting to many people. To understand...read more

Constructors in C++ and its Types
Constructors in C++ and its Types
Constructors in C++ are the member functions that get invoked when an object of a class is created. There are mainly three types of constructors in C++, Default, Parameterized and...read more

All About C++ Friend Function
All About C++ Friend Function
Friend function in C++ is a non-member function of a class. It is defined outside the class scope but it does have the access to a private data member of...read more

All About Virtual Functions in C++
All About Virtual Functions in C++
In C++, a virtual function is a member function of a class that can be overridden by derived classes. It is declared as virtual in the base class and can...read more

Thus, OOP in C++ is not just a programming style but a way of thinking that aligns software development with real-world concepts. It's a tool that, when used effectively, can lead to the creation of systems that are not only functionally rich but also easy to understand, modify, and maintain. 

FAQs

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

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods). In C++, OOP is crucial because it helps in organizing complex programs, making code more flexible, reusable, and easier to maintain. It revolves around the four basic principles of Encapsulation, Inheritance, Polymorphism, and Abstraction.

How Does Encapsulation Work in C++?

Encapsulation is the OOP principle that binds together the data and functions that manipulate the data and keeps both safe from outside interference and misuse. In C++, encapsulation is implemented using classes. A class encapsulates the data represented by its properties and the methods to manipulate that data within a single cohesive unit. Access specifiers like private, protected, and public determine the accessibility of these class members.

Can You Describe Inheritance and Its Types in C++?

Inheritance is an OOP concept where a new class (derived class) inherits properties and behavior (methods) from an existing class (base class). This mechanism allows for code reuse and the creation of a hierarchical class structure. In C++, inheritance can be of several types, including:

  • Single Inheritance: Where a class inherits from one base class.
  • Multiple Inheritance: Where a class inherits from more than one base class.
  • Multilevel Inheritance: Where a class inherits from a base class, which in turn inherits from another base class.
  • Hierarchical Inheritance: Where multiple classes inherit from a single base class.
  • Hybrid Inheritance: A combination of two or more types of inheritance.

What is Polymorphism in C++, and How is it Achieved?

Polymorphism is the OOP concept that allows objects of different classes to be treated as objects of a common super class. It enables a single interface to represent different underlying forms (data types). In C++, polymorphism is achieved through:

  • Function Overloading: Same function name with different parameters in the same scope.
  • Operator Overloading: Providing a special meaning to an existing operator within the same scope.
  • Virtual Functions and Dynamic Binding: Using virtual functions, C++ allows in runtime to decide which method to invoke based on the type of the object that invokes the method.

What is Abstraction, and Why is it Useful in C++?

Abstraction is the principle of hiding the complex reality while exposing only the necessary parts. It means that the user interacts with only the necessary details of an object, while the inner workings are hidden. In C++, abstraction is achieved using abstract classes and interfaces. This concept is useful for reducing complexity and allowing the programmer to focus on interactions at a higher level. It makes the program easier to understand and modify.

What is the Role of Constructors in C++?

Constructors in C++ are special member functions used to initialize objects. They are automatically called when an object is created and can be overloaded to initialize objects in different ways.

What are Destructors in C++ and When are They Used?

Destructors are special member functions in C++ that are executed when an object goes out of scope or is explicitly deleted. Their main purpose is to free resources that were allocated to the object during its lifetime.

How Do Access Specifiers Enhance Encapsulation in C++?

Access specifiers like public, private, and protected control the visibility of class members. They are fundamental to encapsulation in C++ as they help in safeguarding the data by restricting unauthorized access and modifications.

What are Virtual Functions, and How Do They Enable Polymorphism in C++?

Virtual functions are functions that are designed to be overridden in derived classes. When a base class declares a function as virtual, C++ ensures that the most derived function is called for an object, regardless of the type of reference (or pointer) used for the function call. This mechanism is central to achieving runtime polymorphism.

What is the Significance of the this Pointer in C++?

The this pointer in C++ is a special pointer that points to the object that invokes a member function. It can be used to refer to the calling object from within a member function, particularly when handling operations involving assignment or comparison to self.

Can You Explain Operator Overloading and Its Purpose in C++?

Operator overloading allows developers to redefine the way C++ operators work for user-defined types. This feature enables more intuitive code and operations on complex objects, such as concatenating two custom string objects with the + operator.

What are Friends Functions and Friend Classes in C++?

Friend functions and friend classes can access private and protected members of other classes in which they are declared friends. This concept allows for certain exceptions to the typical encapsulation rules, which can be useful in some specific design situations.

How are Pure Virtual Functions Used to Achieve Abstraction in C++?

Pure virtual functions are declared by assigning 0 in their declaration. They make a class abstract, meaning it cannot instantiate objects. This is used to create interfaces and enforce subclasses to implement these functions, thereby achieving abstraction.

What is Multiple Inheritance and What are Its Challenges in C++?

Multiple inheritance allows a class to inherit from more than one base class. This feature lets a class combine behaviors and attributes from more than one source class. However, it can lead to complications like the Diamond Problem, where an ambiguity arises due to multiple paths to the same base class.

What is the Use of static Members in C++ Classes?

Static members of a class in C++ are shared by all instances of the class. They are useful when you need a common value to be available to all objects of the class, such as a counter of how many objects have been instantiated.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio