Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Inheritance is a fundamental concept in C++ that allows one class to inherit properties and behaviors from another. This powerful feature of object-oriented programming promotes code reusability and establishes a natural hierarchy between classes. By leveraging inheritance, you can create more specialized and refined classes based on existing ones, thereby enhancing code organization and reducing redundancy. In this blog, we will explore the principles of inheritance in C++, including different types of inheritance, its benefits, and practical examples to help you understand how to effectively utilize inheritance in your C++ programs.
What is Inheritance in C++?
Inheritance in C++ is a mechanism that allows a new class, known as the derived class, to inherit properties and methods from an existing class, called the base class. This concept enables code reuse and establishes a hierarchical relationship between classes. By inheriting from a base class, the derived class can access and extend the functionality of the base class, leading to more organized and maintainable code. Inheritance supports various types of relationships, including single inheritance, multiple inheritance, and hierarchical inheritance, each allowing for different levels of class interaction and reuse.
Syntax of Inheritance in C++
In C++, inheritance is defined using the : symbol followed by the access specifier (public, protected, or private). Here’s the basic syntax:
class BaseClass {
// Base class members
};
class DerivedClass : accessSpecifier BaseClass {
// Derived class members
};
BaseClass is the class being inherited from.
DerivedClass is the class that inherits from BaseClass.
accessSpecifier determines the access level of base class members in the derived class (public, protected, or private).
How to Make a Private Member Inheritable?
In C++, private members of a base class are not directly accessible by derived classes. However, you can make private members inheritable by providing public or protected accessors in the base class. This way, derived classes can interact with private members through these accessible functions. Here’s how to achieve this:
1. Use Protected Access Specifier:
Change the private members to protected in the base class. This makes them accessible to derived classes while keeping them hidden from outside code.
Example:
class Base {
protected: int protectedMember;
public: void setProtectedMember(int value)
{
protectedMember = value;
}
int getProtectedMember() {
return protectedMember;
}
};
class Derived : public Base { public: void accessProtectedMember() { // Can access protectedMember through Base class methods setProtectedMember(10); int value = getProtectedMember(); } };
2. Provide Public or Protected Accessor Methods:
Define public or protected methods in the base class to allow derived classes to interact with private members without directly exposing them.
Example:
class Base {
private:
int privateMember;
protected:
void setPrivateMember(int value) {
privateMember = value;
}
int getPrivateMember() const {
return privateMember;
}
};
class Derived : public Base {
public:
void modifyPrivateMember(int value) {
// Access privateMember indirectly through Base class methods
setPrivateMember(value);
int value = getPrivateMember();
}
};
Implementing inheritance in C++
The following syntax is used to implement inheritance in C++
class derived_class_name : access_mode base_class_name
{
//body of the derived class
};
Access Specifiers
Access specifiers are the keywords used to control the accessibility of classes, methods, and other class members. It also ensures what functions and properties are inherited when a class is derived from another class.
In C++, we have three access specifiers:-
Public: The members that are public in the base class are derived as public in the derived class if derived publicly. These are accessible from anywhere outside the class.
Private: Public or protected members of the base class become private members of the derived class when inherited privately. Private members are never inherited.
Protected: The protected members cannot be accessed outside the class, but they can be inherited.
By default, all members and functions in C++ are private.
The following table shows how the various access specifiers work when a class is inherited from another class.
Key points from the above table
Private members are never inherited.
If publicly inherited, public members will be public and protected members will be protected.
If we inherit under a protected specifier, public and protected members become protected.
Protected members cannot be accessed in the driver function directly, just like private members; they can be accessed using other public or private or protected member functions.
Types of Inheritance
SINGLE INHERITANCE
When we have only one base class and one derived class, such an inheritance is called single inheritance. It is the most common and most used inheritance type.
The downward arrow shows that class B is derived from class A in the above diagram. This means that all the members and functions of class A defined as public or protected are inherited by class B, which means the objects of class B can use the methods and properties of class A.
Example of Single Inheritance in C++
C++
C++
#include<iostream> using namespace std;
//defining base_class class base_class{ public: int data;
//a function to set the value of data void set_data(int new_data){ data = new_data; }
//a function to get the value of data int get_data(){ return data; } };
//derivinf class from base class class derived_class: public base_class{ public: int data2; void print_message(){ cout<<"Method of derived class"; } };
int main(){
//creating object of derived class derived_class obj;
//calling fucntion of base class by an object of derived class obj.set_data(55); cout<<obj.get_data()<<endl;
//accessing additional features of derived class obj.data2 = 10; cout<<obj.data2<<endl; obj.print_message();
return 0; }
You can also try this code with Online C++ Compiler
When a class is derived with more than one base class, such an inheritance is called multiple inheritances.
Class C is derived from class A and B in the above example. Class C will have all the properties and methods of classes A and B.
Ambiguity in multiple inheritances
In a case where both the base classes have a function with the same name, there arises an ambiguity as to which method to use when called by an object of the derived class. At this time, the compiler shows an error due to the ambiguity that arose.
Example of Multiple Inheritance in C++
C++
C++
#include<iostream> using namespace std;
//defining base_class A class A{ public: int data;
//a function to set the value of data void set_data(int new_data){ data = new_data; }
//a function to get the value of data int get_data(){ return data; } };
//defining base_class B class B{ public: void print_base_class2(){ cout<<"This is a method of class B\n"; }
};
//deriving class from base classes A and B class derived_class: public A, public B{ public: int data2; void print_message(){ cout<<"Method of derived class"; } };
int main(){
//creating object of the derived class derived_class obj;
//calling function of class A by an object of derived class obj.set_data(55); cout<<obj.get_data()<<endl;
//calling function of class B by an object of derived class obj.print_base_class2();
//accessing additional members of derived class obj.data2 = 10; cout<<obj.data2<<endl; obj.print_message();
return 0; }
You can also try this code with Online C++ Compiler
When we derive a class from an already derived class.
In the above example, class C is derived from class B, which is already derived from class A.
A = base class
B = properties of A + additional properties
C = properties of B + additional properties
Example of Multilevel Inheritance in C++
C++
C++
#include<iostream> using namespace std;
//defining base class A class A{ public: int data;
//a function to set the value of data void set_data(int new_data){ data = new_data; }
//a function to get the value of data int get_data(){ return data; } };
//deriving class B from class A class B: public A{ public: void print_message(){ cout<<"Method of class B\n"; } int triple_data(){ return 3*data; } };
//deriving class C from class B class C: public B{ public: void print_statement(){ cout<<"Method of class C\n"; } int double_data(){ return 2*data; } };
//driver function int main(){
//creating an object of class C C obj;
//accessing functions of class A from an object of class C obj.set_data(55); cout<<obj.get_data()<<endl;
//accessing functions of class B from an object of class C obj.print_message(); cout<<obj.triple_data()<<endl;
//accessing additional functions of class C obj.print_statement(); cout<<obj.double_data();
return 0; }
You can also try this code with Online C++ Compiler
It is a mixture of both the multiple and the multilevel inheritance. A class is derived from two or more classes, and one of the parent classes is not a derived class.
Here, class D is derived from classes B and C, which are inherited from class A.
Example of Hybrid Inheritance in C++
C++
C++
#include<iostream> using namespace std;
//defining base class A class A{ public: int data;
//a function to set the value of data void set_data(int new_data){ data = new_data; }
//a function to get the value of data int get_data(){ return data; } };
//deriving class B from class A class B: public A{ public: void print_message(){ cout<<"Method of class B\n"; } };
//deriving class C from class A class C{ public: void print_statement(){ cout<<"Method of class C\n"; } };
//deriving class D from B and C class D: public B, public C{ public: void print_function(){ cout<<"Method of class D\n"; } };
//driver function int main(){
D obj;
//accessing functions of class A obj.set_data(55); cout<<obj.get_data()<<endl;
55
Method of class B
Method of class C
Method of class D
Advantages of Inheritance
If we create an application based on this approach, it will have the following benefits:
The time it takes to design an application is reduced.
The application uses less memory.
The time it takes for an application to run is reduced.
The performance of the application has been improved (improved).
The code's redundancy (repetition) is decreased or eliminated, resulting in more consistent outputs and lower storage costs.
Disadvantages of Inheritance
Tight Coupling: Derived classes are closely tied to their base classes, leading to increased dependency. Changes in the base class can affect all derived classes, potentially causing maintenance issues.
Complexity: Inheritance hierarchies can become complex, especially with deep or multiple inheritance. This can make the codebase harder to understand and maintain.
Fragile Base Class Problem: Modifications to a base class can unintentionally break derived classes if not carefully managed. This is known as the "fragile base class problem."
Inheritance Overuse: Overusing inheritance, especially in cases where composition would be more appropriate, can lead to code that is difficult to extend and modify.
Performance Overheads: In some cases, inheritance can introduce performance overheads due to additional function calls or the need for virtual table lookups.
Hidden Dependencies: Derived classes may inadvertently depend on the internal implementation details of the base class, leading to hidden dependencies and reduced flexibility.
Inheritance helps us determine a class in another class, making application development and maintenance easier. This also allows for the reuse of code functionality and a quick implementation time.
What is protected inheritance in c++?
In protected inheritance, the public and protected members of the base class are protected in the derived class.
What is the use of access modifiers in C++?
Object-oriented programming relies heavily on access modifiers. They're utilised to put OOP encapsulation into practice. You can use access modifiers to control who has and doesn't have access to particular functionalities.
How many types of inheritances are there in C++?
The five types of inheritances are single, multiple, multilevel, hierarchical, and hybrid inheritance.
Why are multiple inheritances not supported by JAVA?
Multiple inheritances cause ambiguity. When we have a function with the same name in both the classes, the compiler cannot decide which function to inherit; therefore, it is not supported by java.
Conclusion
In this article, We discussed Inheritance in C++. Inheritance is a key feature of C++ that enables the creation of a hierarchical class structure, promoting code reuse and extending functionality. By understanding and applying inheritance, you can create more organized and maintainable code, leveraging existing class definitions to build new, specialized classes.