Object-oriented programming in C++ is a basic yet important programming paradigm that improves the modularity, reusability, and maintainability of the code. C++ is one of the most widely used object-oriented programming languages that provides various features to programmers.
In this article, we will discuss what is object oriented programming, basic concepts of object-oriented programming in C++, advantages and disadvantages of object-oriented programming, practical applications of object-oriented programming in C++, why do we need object-oriented programming in C++, difference between object-oriented programming and procedural programing, and why is C++ partially object oriented programming.
Table of Contents:
What is Object Oriented Programming?
Object-oriented programming (OOP) is a programming paradigm that helps programmers to organize code with objects and classes rather than functions or logic. In C++, OOP provides basic features to structure the programs in such a way that improves modularity, reusability, and maintainability of the code. Also, it can be easily implemented in real-life entities with the help of objects.
Basic Concepts of OOP in C++
There are six basic concepts of object-oriented programming, which provide different functionalities. The list of these concepts is given below:
- Classes
- Objects
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
Apart from these six basic pillars of OOPs, there are two more important concepts in this programming system, i.e., message passing and dynamic binding. We will discuss all these concepts in detail in the section given below:
1. What are Classes in C++?
A class in C++ is one of the basic concepts of object-oriented programming. It is a user-defined data type that works as a blueprint for creating objects. A class is also known as a building block of OOP. It is used to define the attributes (data members) and behaviors (member functions) that the objects of that class will have. For example, if we create a class “vehicle”, then “car”, “bike”, and “scooter” can be the objects of this class.
Structure of a Class in C++
A class in C++ consists of three main components:
- Data Members: These are the variables that store the attributes of the class.
- Member Functions: These are the functions that define the behavior of the class.
- Access Specifiers: These are the keywords, such as public, private, and protected, that control access to the class members.
Syntax of a Class in C++
class ClassName {
private:
// Private data members(only accessible inside the class)
public:
// Public data members (accessible outside the class)
// Methods (functions)
};
2. What are Objects in C++?
An object is an instance of a class and one of the basic concepts of object-oriented programming in C++. It represents a real-world entity that contains both data (attributes) and functions (behavior).
Key Points About Objects:
- Objects are created from a class.
- Each object has its own copy of data members.
- Objects allow interaction with class methods to perform operations.
Objects have an identity, state, and behavior. Identity is the name that we use to refer to that object. The state of an object refers to the information that is related to it, and the behavior represents the action of the object that can modify its state. For example, a person has an identity (name), state ( age, weight, height), and behavior (speaking, walking, eating).
Syntax for Creating an Object in C++:
class ClassName {
// Class definition
};
int main() {
ClassName objectName; // Creating an object
return 0;
}
Now, we will create a simple class with an object that will access the data members.
Output:
The code shows how a “Student” class with the attributes “name, rollnumber, and marks” is created at first and displayed using the display() method, then in the main() function, an object “student1” is created with the values assigned to it and its details are printed to the console using the display() method.
3. Encapsulation in C++
In C++, encapsulation means binding together the related data and functions within a single unit called a class. This organizes the code and also protects the encapsulated data from direct manipulation from outside the class. This is also called as data or information hiding. It enhances code security and maintainability.
To understand this with an analogy, consider a capsule. It encapsulates medicine inside it, and the outer cover protects the medicine from external conditions. Similar to this encapsulation is the method that is used to protect the data members and member functions from being directly accessed.
You can modify the access to a class. There are three types of access modifiers in C++, and those are:
- Public: The members declared as public are accessible from outside the class.
- Private: The private members of a class are not accessible from outside the class. These can only be accessed within the class itself.
- Protected: The protected members are similar to private members but have limited accessibility to derived classes. Protected members are accessible within the class and its derived classes.
Note: If you do not mention any access specifier while creating the class, then the class will be private by default.
Example:
Output:
The code shows that the class AccessExample has members with three access specifiers: public, private, and protected, and in the main() function, public members are directly accessed, and the private and protected members can be accessed only within that function.
4. Abstraction in C++
The concept of abstraction is closely related to encapsulation. Abstraction in object-oriented programming hides the implementation details and only shows the important functionalities to the user. It can be achieved by using abstract classes and pure virtual functions.
For example, if you are using a map to navigate a city, and then the map does not show every building, street sign, or tree to you, it will provide essential information about the layout of the city, which helps you navigate the city without getting lost.
Example:
Output:
The code shows that a class “AbstarctionExample” is created with the two private data members a and b, which makes sure that there is encapsulation, as it provides public methods setvalues() to assign values and display() method to print the values. In the main() function, an object is created with the values 20 and 40, and then these values are printed to the console.
5. Inheritance in C++
Inheritance is a concept of OOP in C++, using which a “new class” or “child class” or “derived class” inherits the features and behavior of an “existing class” or “base class” or “parent class”.
The derived class is the extended version of the base class, maintaining the existing properties while introducing its distinct attributes. Inheritance promotes code reusability and the creation of a hierarchy of classes with shared characteristics.
There are five different types of inheritance in C++, which are listed below:
- Single Inheritance: In single inheritance, one class inherits from another class.
- Multiple Inheritance: In multiple inheritance, a class inherits from multiple base classes.
- Multilevel Inheritance: In multilevel inheritance, a class inherits from another derived class.
- Hierarchical Inheritance: In hierarchical inheritance, multiple derived classes inherit from a single base class.
- Hybrid Inheritance: It is a combination of two or more types of inheritance.
Example:
Output:
The code shows the single inheritance in which the Dog class inherits the eat() method from the Animal class while defining its own bark() method, and in the main() function, a Dog object is created that can access both the functions easily.
6. Polymorphism in C++
Polymorphism means “having many forms”. It is the capability of a message or operation to be utilized in many ways. In other words, an object can have multiple characteristics or behaviors. Much like how a person can simultaneously play the roles of a father, a husband, and an employee, demonstrating different behaviors in different situations, this process is known as polymorphism.
In programming, polymorphism is expressed through operations that can behave differently based on the types of data involved. C++ facilitates polymorphism through features like compile-time polymorphism and run-time polymorphism.
- Compile-time polymorphism: This type of polymorphism is obtained through operator or function overloading.
- Run-time polymorphism: Run-time polymorphism is achieved through function overriding.
Example:
Output:
The code shows polymorphism, as the function multiplyNumbers() is called twice in the program, but with a different number of arguments, and this function is modified based on our needs. First, we are multiplying two numbers and then three numbers, and later the output is printed ot the console.
7. Message Passing in C++
Message passing in C++ is also a basic concept in object-oriented programming in which objects communicate with each other by calling methods or member functions. In other words, we can say that they communicate by passing information to each other, which is similar to messaging. A message is a request for the implementation of a function. The object that receives the message invokes the function to generate the desired output. The process involves stating the name of the object, the name of the function, and the message (information to be sent). It also helps in encapsulation and making code modular.
Example:
Output:
The code shows the message passing by showing communication between the Customer object and BankAccount object by calling the methods such as depositMoney(), withdrawMoney(), and showBalance(), which make sure that there is encapsulation and controlled access to the account balance.
8. Dynamic Binding in C++
Dynamic binding in C++ is the process of linking together the function call and the code to be executed in response to that call. Dynamic binding is also known as “Late binding”, which means that the code, which is going to be executed in response to the function call, is decided at run-time, unlike static binding, where it is decided during build-time. It is achieved using virtual functions and base class pointers or references.
How It Works:
1. Virtual Function Table (VTable)
When a class has a virtual function, then the compiler creates a VTable (Virtual Table) for that class, and the VTable stores function pointers to the actual functions, which should be called at runtime.
2. Virtual Table Pointer (VPTR)
Each object of a class containing virtual functions has a hidden pointer (vptr) to the VTable, and at runtime, the correct function is called using this vptr, which allows function overriding in derived classes.
Example:
Output:
The code shows that the base class Shape contains a virtual function draw(). The derived classes Circle and Rectangle both override this function, and in the main() function, a variable of type pointer Shape* can refer to instances of the Circle class as well as the Rectangle class. This illustrates dynamic binding. Afterwards, the draw() method is invoked, depending on the actual object being pointed to.
Advantages of Object-Oriented Programming in C++
- The object-oriented programming in C++ provides important features such as encapsulation, abstraction, inheritance, and polymorphism, which provide different functionalities.
- It also helps to write modular code by breaking down complex programs into simple, manageable, and reusable objects.
- OOP provides extensibility, which makes it easier to add new features without changing the existing code.
- It gives better data management and improves code reusability.
- It allows designing the software similar to real-world entities by message passing and dynamic binding.
Disadvantages of Object-Oriented Programming in C++
- Object-oriented programming increases the complexity of the code because it uses multiple concepts in a single program.
- It has a slower execution speed due to dynamic binding and virtual function calls.
- It uses more memory as the objects need more storage.
- OOP is not suitable for small programs because it can lead to overhead due to defining objects and classes.
- It gives higher debugging complexity with multiple layers of inheritance and polymorphism.
Practical Applications of OOPs in C++
There are many real-life systems where OOP has been used. These systems are very complex and difficult to build. But OOP has made this task easier. Given below are some examples where OOP is used.
- The GUI (Graphical User Interface) design is like Windows. Many Windows systems have been developed using OOP methods.
- In object-oriented databases.
- In embedded systems like medical devices and home appliances.
- In the browser’s components, such as the rendering engine, network stack, and JavaScript interpreter.
- In structuring operating systems.
- In game development.
Why do we need OOPs in C++?
The main reason why we need OOP is code reusability, which means the ability to use the same code again and again in the program. It saves a lot of time, as there is no need to create new functions for every similar situation. This facility was not present in the procedural programming paradigm. It is a better programming style than functional programming, as it also provides code safety by using functionalities such as data abstraction and encapsulation.
Object-Oriented Programming vs. Procedural Programming
Aspect |
Procedural Programming (PP) |
Object-Oriented Programming (OOP) |
Approach |
Top-down approach |
Bottom-up approach |
Program Structure |
Step-by-step instructions, harder to maintain |
Objects combining data and methods, easier to maintain |
Division of Program |
Divided into functions |
Divided into objects |
Focus |
Functions are primary, data is secondary |
Data is primary, functions operate on data |
Data Security |
No data hiding, less secure |
Uses encapsulation, better security |
Code Reusability |
Not possible |
Possible through inheritance |
Scalability |
Difficult to modify and scale |
Easy to extend and maintain |
Real-World Representation |
Not based on real-world concepts |
Based on real-world entities (objects) |
Adding New Features |
Complex to add new functions or data |
Easy to add new functions and data |
Data Handling |
Data is global, accessible to all functions |
Data is encapsulated within objects |
Polymorphism |
Not supported |
Supported (method overloading and overriding) |
Best Suited For |
Small programs and simple applications |
Large, complex, and scalable applications |
Execution Speed |
Faster due to direct function calls |
Slightly slower due to dynamic binding |
Examples of Languages |
C, BASIC, PASCAL, COBOL |
C++, Java, Python, C# |
Why is C++ Partial Object-Oriented Programming?
Below are the reasons why C++ is partially object-oriented:
- C++ supports both procedural programming and object-oriented programming concepts, thus, it is considered partially object-oriented.
- Also, it uses global functions outside of the classes and supports basic data types such as int, char, and float without encapsulation.
- The friend functions and private members of a class can be accessed in C++ without breaking the encapsulation principle.
- Also, the static methods can be used without creating an object in C++.
Conclusion
From the above discussion, we can conclude that the concepts of object-oriented programming in C++ help in the organization, security, and reusability of the code. The main OOP concepts include classes, objects, encapsulation, abstraction, inheritance, polymorphism, message passing, and dynamic binding. It is beneficial in designing and developing complex systems such as GUIs, databases, embedded systems, and many more. All these functionalities make OOPs a very useful concept. So, by understanding object-oriented programming, you can write an efficient C++ program by using the concepts.
FAQs on Object-Oriented Programming in C++
View saved revision
Q1. What is Object-Oriented Programming (OOP) in C++?
OOP is a programming paradigm that organizes code using objects and classes and improves the modularity, reusability, and maintainability of the code.
Q2. What are the core principles of OOP?
The core principles of OOP are encapsulation, abstraction, inheritance, and polymorphism.
Q3. What is the difference between a class and an object?
The difference between a class and an object is that a class is a blueprint, and an object is an instance of a class.
Q4. What is encapsulation in C++?
Encapsulation in C++ is the bundling of data and methods within a class while restricting direct access.
Q5. How is abstraction achieved in C++?
Abstraction in C++ is achieved by using abstract classes and pure virtual functions.