Class in C++
A class in C++ is a blueprint for creating objects. It defines a type of data that encapsulates data & methods that operate on that data. In simple terms, a class organizes information & functions under a single unit. This unit can be used repeatedly to create multiple objects, each sharing the same properties & behaviors but holding different data values.
Example of a Class in C++
Let’s create a basic class to represent a book:
C++
#include <iostream>
using namespace std;
class Book {
public:
string title;
string author;
int pages;
void printDetails() {
cout << "Book: " << title << "\nAuthor: " << author << "\nPages: " << pages << endl;
}
};
int main() {
Book book1;
book1.title = "C++ for Beginners";
book1.author = "Ravi Singh";
book1.pages = 300;
book1.printDetails(); // Output the details of the book
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Book: C++ for Beginners
Author: Ravi Singh
Pages: 300
In this example, Book is a class with three attributes (title, author, pages) & one method (printDetails()). The main() function creates an object book1 of the Book class, assigns values to its attributes, & calls the printDetails() method to display the information. Each object of the class Book can hold different values, making the class a versatile & reusable component of C++ code.
Objects in C++
An object in C++ is an instance of a class. When a class serves as a template, an object is the actual entity you work with in your code. Each object has its own set of values that occupy memory & can be manipulated. Essentially, while a class defines the structure, objects fill that structure with real data.
Example of Creating & Using Objects
Continuing with our Book class from before, let's see how we can create & use multiple objects:
C++
#include <iostream>
using namespace std;
class Book {
public:
string title;
string author;
int pages;
void printDetails() {
cout << "Book: " << title << "\nAuthor: " << author << "\nPages: " << pages << endl;
}
};
int main() {
// Create two objects of the Book class
Book book1, book2;
// Assign data to book1
book1.title = "C++ for Beginners";
book1.author = "Pallavi Singh";
book1.pages = 300;
// Assign data to book2
book2.title = "Advanced C++ Programming";
book2.author = "Ravi Kumar";
book2.pages = 500;
// Output the details of both books
book1.printDetails();
book2.printDetails();
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Book: C++ for Beginners
Author: Pallavi Singh
Pages: 300
Book: Advanced C++ Programming
Author: Ravi Kumar
Pages: 500
In this code, book1 & book2 are objects of the Book class. Each has its own set of attributes filled with unique values. The method printDetails() is called on both objects, demonstrating how each object retains its own state & behavior as defined by the class template.
Objects are the crucial component of object-oriented programming in C++. They make it possible to use code as building blocks for larger & more complex programs. By using objects, developers can better organize code, make it reusable, & keep data & the methods that modify that data together in one place.
Encapsulation in C++
Encapsulation is a fundamental object-oriented programming (OOP) concept used to bundle the data (attributes) and the methods (functions) that manipulate the data into a single unit, or class. In C++, encapsulation helps to protect against unauthorized access and misuse of the class members.
How Encapsulation Works
In C++, you achieve encapsulation by using access specifiers to control the accessibility of the class members. The most common access specifiers are private, public, and protected:
- Private: Members declared as private are accessible only within the same class and cannot be accessed from outside the class.
- Public: Members declared as public are accessible from any part of the program.
- Protected: Members declared as protected can be accessed by the class itself and by its subclasses and friend classes.
Example of Encapsulation in C++
C++
#include <iostream>
using namespace std;
class Employee {
private:
int salary; // Private attribute
public:
// Setter function to set the salary
void setSalary(int s) {
salary = s;
}
// Getter function to get the salary
int getSalary() {
return salary;
}
};
int main() {
Employee emp;
emp.setSalary(50000); // Setting the private attribute using the setter
cout << "Salary: " << emp.getSalary() << endl; // Getting the private attribute using the getter
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Salary: 50000
In this example, the Employee class has a private attribute salary that can't be accessed directly from outside the class. Instead, access to salary is controlled through public methods setSalary() and getSalary(). This setup ensures that the salary cannot be changed arbitrarily; it can only be modified through the setSalary method, which might contain validation logic to prevent invalid salary values.
Encapsulation enhances the maintainability and robustness of the code by safeguarding data and hiding implementation details. It allows developers to change one part of the code without affecting other parts.
Abstraction in C++
Abstraction is another main but important concept in object-oriented programming that helps hide the complex reality while exposing only the necessary parts of an object. In C++, abstraction means focusing on what an object does instead of how it does it by using classes to separate interface and implementation.
Understanding Abstraction
Abstraction can be achieved with either abstract classes or interfaces, which allow you to create methods that must be implemented within any child classes. In C++, abstract classes are typically used to define interfaces for other classes to implement.
Example of Abstraction in C++
C++
#include <iostream>
using namespace std;
// Abstract class
class Animal {
public:
// Pure virtual function providing interface framework.
virtual void speak() = 0;
};
// Derived class
class Dog : public Animal {
public:
void speak() {
cout << "Woof!" << endl;
}
};
int main() {
Dog myDog;
myDog.speak(); // Calls the speak function defined in Dog
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Woof!
In this example, Animal is an abstract class because it contains at least one pure virtual function (speak()). The class Dog inherits from Animal and implements the speak() function. Here, the Animal class provides a simple interface for all animals to follow, but each subclass of Animal can determine how to implement speaking. This is abstraction in action: you know that each animal speaks, but not how each animal does it until you see the implementation in each subclass.
Abstraction reduces complexity by hiding unnecessary details and showing only essential features of an object. It helps in managing larger software projects by enabling programmers to consider a more manageable problem space. It also enhances model extensibility by allowing the same functions to work on different kinds of data inputs.
Polymorphism in C++
Polymorphism is another important concept in object-oriented programming (OOP) used in C++. It refers to the ability of a function to handle objects of many types. This means that a single function can work with different data types and classes at the same time, depending on the object it is interacting with.
How Polymorphism Works
In C++, polymorphism is primarily achieved in two ways: through overloading and overriding.
- Overloading allows multiple functions to have the same name but different parameters. This means you can have several versions of a function that do similar things but with different types or numbers of inputs.
- Overriding involves redefining a function in a derived class that has been defined in its base class. It allows a child class to provide a specific implementation of a method that is already provided by one of its parent classes.
Example of Polymorphism in C++
C++
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
virtual void sound() {
cout << "Some sound" << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void sound() override {
cout << "Woof!" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Meow!" << endl;
}
};
void makeSound(Animal& a) {
a.sound();
}
int main() {
Dog myDog;
Cat myCat;
makeSound(myDog); // Outputs: Woof!
makeSound(myCat); // Outputs: Meow!
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Woof!
Meow!
In this example, the Animal class has a virtual method sound(), and the classes Dog and Cat override this method to provide specific sounds for dogs and cats, respectively. The function makeSound() takes a reference to an Animal object and calls the sound() method. Depending on the actual object passed (Dog or Cat), the corresponding sound() method is called, demonstrating polymorphism.
Polymorphism allows for flexibility and simplicity in code. It lets programmers use the same code to work with different types of objects, simplifying programming and increasing the effectiveness of the code by handling different data types and class hierarchies more efficiently.
Inheritance in C++
Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit attributes and methods from another. This feature supports the creation of a new class based on an existing class, which helps to reduce redundancy in code and enhance the reusability of existing classes.
How Inheritance Works in C++
Inheritance in C++ is implemented by creating a new class (known as a derived or child class) that inherits the properties from an existing class (known as the base or parent class). The child class can inherit all or selected attributes and methods of the parent class, making it possible to extend or modify the behaviors of the parent class without modifying the original code.
Example of Inheritance in C++
C++
#include <iostream>
using namespace std;
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Beep, beep!" << endl;
}
};
// Derived class
class Car : public Vehicle {
public:
string model = "Mustang";
void display() {
cout << "Brand: " << brand << ", Model: " << model << endl;
}
};
int main() {
Car myCar;
myCar.honk(); // Calls the honk method from the base class
myCar.display(); // Outputs: Brand: Ford, Model: Mustang
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Beep, beep!
Brand: Ford, Model: Mustang
In this code, Car is the derived class that inherits from the Vehicle class. The Car class has access to the brand attribute and the honk() method of the Vehicle class, along with its own attributes and methods. This example demonstrates how inheritance can be used to extend the functionalities of base classes by adding new features in the derived classes.
Inheritance allows developers to create a new class from an existing class. The new class contains the combined features of the old class plus additional enhancements. It helps in reducing code duplication and increases the code maintainability by allowing changes to be made in just one place in the hierarchy.
Dynamic Binding in C++
Dynamic binding, also known as late binding, is a concept in C++ that allows a program to decide what function to call at runtime based on the object that is used to call the function. This is different from static binding, which resolves the function call at compile time.
Understanding Dynamic Binding
Dynamic binding is crucial for achieving polymorphism in object-oriented programming. It enables a program to select the appropriate method at runtime, which is especially useful when the method to be used is not known at compile time.
Example of Dynamic Binding in C++
C++
#include <iostream>
using namespace std;
// Base class with a virtual function
class Animal {
public:
virtual void makeSound() {
cout << "Some generic sound" << endl;
}
};
// Derived class overrides the virtual function
class Dog : public Animal {
public:
void makeSound() override {
cout << "Woof!" << endl;
}
};
// Another derived class
class Cat : public Animal {
public:
void makeSound() override {
cout << "Meow!" << endl;
}
};
void performSound(Animal& animal) {
animal.makeSound(); // Sound depends on the type of the object
}
int main() {
Dog dog;
Cat cat;
performSound(dog); // Outputs: Woof!
performSound(cat); // Outputs: Meow!
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Woof!
Meow!
In this example, performSound() takes a reference to an Animal object and calls the makeSound() method. Because the method is virtual and the classes Dog and Cat override it, the C++ runtime checks the type of the actual object and calls the appropriate method. This happens at runtime, hence the term "dynamic binding."
Dynamic binding allows for more flexible and reusable code. It lets the program handle different types of objects through the same interface, and the actual behavior is determined at runtime based on the object's actual type. This is particularly useful in complex systems where the behavior of objects may not be fully known or may change.
Message Passing in C++
Message passing in object-oriented programming (OOP) is the process by which an object sends data to another object or asks the other object to invoke a method. It can be seen as the OOP way of calling functions and exchanging data between objects.
How Message Passing Works
In C++, message passing is implemented through calling methods on objects. When an object calls a method, it sends a message to another object (which could be itself) to perform a specific operation. This can include requesting data or triggering changes in the state of the object.
Example of Message Passing
To illustrate how message passing works, let’s use a simple example involving a class that represents a Student and a class that represents a University:
C++
#include <iostream>
using namespace std;
// Class representing a Student
class Student {
public:
string name;
int age;
// Constructor to initialize the Student object
Student(string n, int a) : name(n), age(a) {}
// Method to display student details
void displayInfo() {
cout << "Name: " << name << " Age: " << age << endl;
}
};
// Class representing a University
class University {
public:
// Method to enroll a student and ask to display his information
void enrollStudent(Student& student) {
cout << "Enrolling student:" << endl;
student.displayInfo(); // Message passing to the Student object
}
};
int main() {
Student student1("Ravi Singh", 20);
University uni;
uni.enrollStudent(student1); // Passing message to enroll and display student info
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Enrolling student:
Name: Ravi Singh Age: 20
In this code, the University class has a method enrollStudent that takes a Student object and calls its displayInfo method. This is an example of message passing where the University object sends a message to the Student object to perform an operation (displayInfo). This process allows objects to interact and cooperate in performing tasks.
Benefits of Message Passing
Message passing is crucial for:
- Encapsulation: It helps in maintaining the privacy of objects' states by not exposing the states directly but instead through methods.
- Modularity: Objects can be understood as separate entities that interact with each other through well-defined interfaces.
- Maintainability: Changes in one part of a system do not ripple through other parts, as communications are done via messages.
Frequently Asked Questions - Oops Concept in C++
What is the difference between a class and an object in C++?
A class is a blueprint for creating objects. It defines the structure and behaviors that the objects created from it will have. An object is an instance of a class, with actual values and characteristics defined by that class.
Why is encapsulation important in object-oriented programming?
Encapsulation is crucial because it helps to protect an object's internal state from unintended or harmful modifications by external code. It allows the internal state to be changed only through well-defined methods, which can include checks and balances to maintain the integrity of the data.
How does polymorphism benefit C++ programming?
Polymorphism enhances flexibility and simplifies code management by allowing methods to interact differently with different object types. This ability lets programmers use a uniform interface to handle different underlying data types, making the code more modular and easier to extend.
Conclusion
In this article, we have learned the foundational concepts of object-oriented programming in C++, including classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing. Understanding these principles allows you to create structured and efficient software that can be easily maintained and scaled. By mastering these concepts, programmers can build effective but versatile applications that leverage the full capabilities of C++, enhancing both performance and productivity.
You can refer to our guided paths on Code360. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.