All About OOPs Concepts in C++

All About OOPs Concepts in C++

11 mins read9.2K Views Comment
clickHere
Esha
Esha Gupta
Associate Senior Executive
Updated on Dec 29, 2023 17:59 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.

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 Overloading And Overriding
Difference Between Overloading And Overriding
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

Conclusion

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. 

About the Author
author-image
Esha Gupta
Associate Senior Executive

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

Comments