In C++, the concept of inheritance involves an object automatically acquiring all the attributes and functionalities of its parent object. This mechanism enables the utilization, expansion, or adjustment of the characteristics and actions specified in different classes.
In C++, a derived class is defined as a class that acquires the members of another class, identified as the base class. The derived class is considered a specialized version of the base class.
Syntax
It has the following syntax:
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}
C++ Basic Example of Inheritance
Let's consider a scenario to demonstrate the concept of C++ Inheritance.
Example
#include <iostream>
using namespace std; //using standard namespace
// Base Class
class Animal {
public: //Access
// Base class member function
void eat() {
cout << "Animal Sounds" << endl;
}
};
// Derived Class
class Dog : public Animal {
public:
// Derived class member function
void bark() {
cout << "Dog Barks" << endl;
}
};
int main() //Main function
{
Dog dog; // Create object of derived class Dog
dog.eat(); // Call base class function using derived class object
dog.bark(); // Call derived class function
return 0;
}
Output:
Animal Sounds
Dog Barks
Explanation
In this illustration, we start with a base class Animal, which has a method eat. Next, we introduce a Dog subclass that extends Animal and introduces its own method, bark. Within the main function, an instance named dog of the Dog class is instantiated. Subsequently, invoking dog.eat will execute the inherited function from Animal, while dog.bark will execute the Dog class's specific function.
Types of Inheritance Classes in C++
There are mainly two classes of C++ inheritance.
1) Base Classes
A foundational class is a class that offers shared characteristics and functions for other classes to derive from. It establishes the attributes and actions that its subclasses can employ or modify, acting as the basis for additional class expansions. It acts as a progenitor and superordinate class.
Syntax
It has the following syntax
class Base_Class{
// members....
// member function
}
2) Derived Classes
A subclass is a class that acquires the attributes and functionalities from its parent class. It may introduce additional functionalities or modify existing ones inherited from the parent class. This type of class is also referred to as a child class or derived class.
Syntax
It has the following syntax:
class Derived_class : public Base_class{
// members....
// member function
}
C++ Inheritance Classes Example:
Let's consider a scenario to demonstrate the concept of inheritance in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Base { //Base Class
public:
int x;
};
class Derived : public Base { //Derived Class
public:
int y;
};
int main() //Main Function
{
// Initialize a Derived class
Derived CppTutorial;
// Assign a value to the Derived class variable
CppTutorial.y = 10;
// Assign a value to the Base class variable via derived class
CppTutorial.x = 15;
cout << "Derived Class Value: " << CppTutorial.y << endl;
cout << "Base Class Value: " << CppTutorial.x << endl;
return 0;
}
Output:
Derived Class Value: 10
Base Class Value: 15
Types of Inheritance
There are mainly five types of inheritance in C++.
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hybrid Inheritance
- Hierarchical Inheritance
Here, we will explore each form of inheritance individually.
1) C++ Single Inheritance
In the C++ programming language, single inheritance is characterized by a scenario where a subclass is derived solely from a single base class.
Where 'A' represents the base class and 'B' represents the derived class.
Syntax
It has the following syntax:
class Base
{
// Body of base class
};
class Derived : public Base
{
// Body of derived class
};
C++ Single Inheritance Example
Let's consider a scenario to demonstrate the concept of single inheritance in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Account { //Base Class
public: //Access Modifier
float salary = 65000;
};
class Programmer: public Account { //Derived Class
public:
float bonus = 5500;
};
int main(void) { //Main Function
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
Output:
Salary: 65000
Bonus: 5500
Explanation
In this instance, a fundamental class named Account and a subclass called Programmer are utilized. Subsequently, this code demonstrates the concept of single inheritance within C++, where the Programmer subclass inherits solely from the Account base class. The instance of Programmer, denoted as p1, can access both the inherited salary and its specific bonus.
To Read More: Single Inheritance
2) C++ Multiple Inheritance
In the C++ programming language, multiple inheritance refers to the mechanism through which a class can acquire the attributes and functionalities of multiple parent classes. With this type of inheritance, a class is able to derive from multiple classes simultaneously. This approach offers increased adaptability and the ability to reuse code, albeit at the expense of introducing additional intricacy into the codebase.
Syntax
It has the following syntax:
class Base1
{
//Body of base class 1
};
class Base2
{
// Body of base class 2
};
class Derived : public Base1, public Base2
{
// Body of the derived class
};
C++ Multiple Inheritance Example
Let's consider a straightforward example to demonstrate the concept of multiple inheritance in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class A //Base class A
{
protected:
int a; //Protected data member
public:
void get_a(int n)
{
a = n;
}
};
class B //Base class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B //Derived Class
{
public:
void display()
{
cout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main() //Main function
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
return 0;
}
Output:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
Explanation
In this instance, the class 'C' derives from two parent classes, 'A' and 'B', using public inheritance. Both classes 'A' and 'B' possess their individual sets of data members and methods. Following this, the show function within class C accesses and combines the values inherited from both classes to display the result.
To Read More: Multiple Inheritance
3) C++ Multilevel Inheritance
C++ Multilevel Inheritance is a principle in which a class is extended from a subclass, forming a sequence of inheritance. There is flexibility in the number of levels that can be implemented. For instance, let's examine a scenario involving three classes: Class A, B, and C. Here, Class A serves as the fundamental class, Class B acts as the intermediary class, and Class C acts as the derived class. This scenario illustrates the concept of one class inheriting from another class, which is subsequently inherited by yet another class.
Syntax:
It has the following syntax.
class Base
{
// body of Base class
};
class Intermediate : public Base
{
//Body of intermediate class
};
class Derived : public Intermediate
{
// Body of derived class
};
C++ Multi Level Inheritance Example
Let's explore a demonstration of multilevel inheritance in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Animal { //Base Class
public: //Access Modifier
void eat()
{
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal //intermediator Class
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog //Derived Class
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) //Main Function
{
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
Output:
Eating...
Barking...
Weeping...
Explanation
In this instance, we showcase multilevel inheritance in C++. Here, the class BabyDog derives from Dog, which in turn inherits from Animal. The instance d1 of BabyDog can utilize functions from all three classes, showcasing inherited actions such as consuming food, vocalizing, and expressing sadness.
To Read More: Multilevel Inheritance
4) C++ Hybrid Inheritance
In C++, hybrid inheritance is when a class inherits from more than one type of inheritance simultaneously. This type of inheritance can encompass aspects of single inheritance, multiple inheritance, multilevel inheritance, and hierarchical inheritance within the class structure.
Syntax
It has the following syntax.
class Base
{
// base class members and statements
};
class Intermediate1 : public Base
{
// intermediate class 1 members and statements
};
class Intermediate2 : public Base
{
// Body of intermediate class 2 members
};
class Derived : public Intermediate1, public Intermediate2
{
// derived class members and statements
};
C++ Hybrid Inheritance Example
Let's consider a straightforward example to demonstrate hybrid inheritance in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class A //Base class
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};
class B : public A //class B derived from Class A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of 'c' : " << std::endl;
cin>>c;
}
};
class D : public B, public C //class D derived from both class B and Class C
{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a, b, c is : " <<a*b*c<< std::endl;
}
};
int main() //Main Function
{
D d;
d.mul();
return 0;
}
Output:
Enter the value of 'a' :
10
Enter the value of 'b' :
20
Enter the value of 'c' :
30
Multiplication of a, b, c is : 6000
To Read More: Hybrid Inheritance
5) C++ Hierarchical Inheritance
In C++, hierarchical inheritance is the concept where multiple classes are derived from a single base class. This inheritance allows us to incorporate shared attributes and behaviors from the base class into the child classes.
Syntax
It has the following syntax.
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
C++ Hierarchical Inheritance Example
Let's consider an example to demonstrate the concept of Hierarchical Inheritance in C++.
Example
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
float triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main() //Main Function
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}
Output:
Enter the length and breadth of a rectangle:
23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5
Explanation
In the given scenario, we are examining two subclasses (Rectangle and Triangle) that inherit from a shared superclass (Shape). The superclass contains a function for receiving measurements, which the subclasses employ to compute and provide the area of a rectangle and a triangle, respectively.
To Read More: Hierarchical Inheritance
Access Specifiers in Inheritance
In C++, access modifiers can be primarily categorized into three groups:
1) Public Inheritance
In the context of public inheritance, all public members of the base class retain their public accessibility in the derived class, while protected members maintain their protected status. This concept effectively demonstrates the "is-a" relationship, as seen in examples like a car being a type of vehicle. In this scenario, a car acquires fundamental attributes of a vehicle, like the ability to start and stop.
2) Protected inheritance
Protected inheritance guarantees that all public and protected members of the base class are protected within the derived class, restricting access from outside the derived class. For instance, in a practical scenario, a StudentRecord may safeguard internal information like scores, while still enabling inheritance-related functionalities.
3) Private inheritance
In private inheritance, all public and protected members of the base class become private in the derived class. This approach is employed when inheritance is intended for code reusability rather than establishing an is-a relationship.
Visibility of Inherited Members
Here is a table outlining the accessibility of inherited properties in C++.
| Base class visibility | Derived class visibility | ||
|---|---|---|---|
| Public | Private | Protected | |
| Private | Not Inherited | Not Inherited | Not Inherited |
| Protected | Protected | Private | Protected |
| Public | Public | Private | Protected |
Effects of Inheritance in C++
In C++, the concept of inheritance influences various aspects of a class in unique manners. Several of these consequences include:
1) Static Members and Inheritance
Static members are associated with the class itself rather than individual instances. These members are shared among all instances of the class and are not part of regular inheritance. Even though a subclass does not directly inherit static members, they can still be accessed using either the base class's name or the subclass's scope.
2) Inheritance's Friend Functions and Classes
Friend functions and friend classes enable external access to private and protected members of a class. They offer versatility in inheritance for closely connected interactions, debugging, operator overloading, and granting specific access to associated functions or utility classes.
3) Constructors and Destructors in Inheritance (C++):
In C++, constructors and destructors play a crucial role in inheritance. They are used to initialize and clean up objects, respectively, in a class hierarchy. When working with inheritance in C++, it is important to understand how constructors and destructors are inherited and called in derived classes. Let's delve into the details of how constructors and destructors work in the context of inheritance in C++.
Constructors and destructors play vital roles in managing the lifecycle of objects in C++. They are fundamental components found within every class, either explicitly declared by the developer or automatically generated by the compiler.
Constructor Behavior in Inheritance
- The derived class does not inherit constructors.
- However, the constructor of the base class is automatically invoked when a derived class object is created.
- The order of constructor execution always follows a top-down approach.
- First, the base class constructor is executed. After that, the derived class constructor is executed.
- If the base class constructor accepts parameters, the derived class must call it directly with an initializer list.
- Destructors are not inherited and are called in reverse order of construction.
- First, the destructor for the derived class is executed, and then the base class's destructor is invoked.
- It ensures that the derived class's resources get released before those of the base class.
Destructor Behavior in Inheritance
C++ Destructor Inheritance Example
Let's explore a C++ illustration demonstrating how destructors work in the context of inheritance.
Example
#include <iostream>
using namespace std;
class Parent
{
public:
Parent()
{
cout << "Parent class constructor is executed" << endl;
}
~Parent()
{
cout << "Parent class destructor is executed" << endl;
}
};
class Child : public Parent
{
public:
Child()
{
cout << "Child class constructor is executed" << endl;
}
~Child()
{
cout << "Child class destructor is executed" << endl;
}
};
int main()
{
Child instance;
return 0;
}
Output:
Parent class constructor is executed
Child class constructor is executed
Child() class destructor is executed
Parent class destructor is executed
Explanation
In this instance, upon instantiation of a Child class object, the Parent class constructor is invoked initially, followed by the Child class constructor. Upon program termination, destructors are invoked in reverse sequence: firstly, the Child destructor, then the Parent destructor, illustrating the sequence of lifecycle for inherited classes.
Polymorphism in Inheritance
In C++ object-oriented programming, polymorphism enables the redefinition of a method from a base class in a subclass, a concept referred to as function overriding. This functionality plays a crucial role in runtime polymorphism, where the specific function execution is decided during program execution rather than during compilation.
C++ Polymorphism in Inheritance Example
Let's explore an illustration of polymorphism in inheritance using C++ now.
Example
#include <bits/stdc++.h>
using namespace std;
class Base
{
public:
void print()
{
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "It is a Derived Function.";
}
};
int main()
{
Derived d_object;
d_object.print();
return 0;
}
Output:
It is a Derived Function.
Explanation
In this instance, the Derived class overrides the print method that was originally defined in the Base class. Upon calling the print method on an instance of the Derived class, the redefined version within the Derived class is executed, leading to the display of "It is a Derived Function" as the output.
C++ Inheritance MCQs
1) What is C++'s default inheritance mode for classes?
- Public
- Private
- Protected
- None
A derived class can access a base class's private members:
- Solely when using public inheritance
- Solely when the base class is declared as a friend of the derived class
3) What is the public inheritance model?
- Has a relationship.
- Uses a relationship.
- Owns a relationship.
- Is a relationship.
4) What happens to the base class's public members when private inheritance occurs?
- Stay public
- Be protected
- Become private
- Not inherit
5) Which access specifier allows a base class member to be accessible only within derived classes rather than outside?
- Public
- Private
- A friend
- Protected