Category: C++ Inheritance

https://zain.sweetdishy.com/wp-content/uploads/2026/02/Inheritance.png

  • Multilevel Inheritance in C++

    Multilevel inheritance is a type of inheritance, where a class is derived from another derived class, creating a chain of inheritance that allows it to pass down its properties and behaviors through multiple levels of classes or inherit from its predecessor.

    Implementing Multilevel Inheritance

    To implement multilevel inheritance, define classes in a hierarchical manner, where one class inherits from another.

    Syntax

    The syntax of multilevel inheritance in C++ −

    classbaseClass{//Here's a base class members};classderivedClass1:public baseClass{// Members of derivedClass1};classderivedClass2:public derivedClass1{// Members of derivedClass2};

    Here,

    • baseClass is the top-level class from where other classes derive.
    • derivedClass1 is the class that inherits from baseClass.
    • derivedClass2 Inherits from derivedClass1, creating a multilevel structure.

    Block Diagram of Multilevel Inheritance

    See the below block diagram demonstrating multilevel inheritance −

    C++ Multilevel Inheritance

    As per the above diagram, “Shape” is the base class, and it is deriving over to “Polygon” class, and “Polygon” class is further deriving over “Triangle” class in order to implement multilevel inheritance.

    Example of Multilevel Inheritance

    In the following example, we are implementing multilevel inheritance −

    #include <iostream>usingnamespace std;// Base classclassShape{public:voiddisplay(){
             cout <<"This is a shape."<< endl;}};// First derived classclassPolygon:public Shape{public:voidsides(){
             cout <<"A polygon has multiple sides."<< endl;}};// Second derived classclassTriangle:public Polygon{public:voidtype(){
             cout <<"A triangle comes under a three-sided polygon."<< endl;}};intmain(){
       Triangle myTriangle;
    
       myTriangle.display();// From Shape
       myTriangle.sides();// From Polygon
       myTriangle.type();// From Trianglereturn0;}

    Output

    This is a shape.
    A polygon has multiple sides.
    A triangle comes under a three-sided polygon.
    

    Explanation

    • Firstly, a base class named Shape has been created with a public method display(), which prints “This is a shape.”
    • Next, the first derived class named Polygon inherits from the Shape (or base class), meaning it gains access to the members of the Shape class, including the display()
    • The second derived class, named Triangle, inherits from the Polygon class, which allows Triangle to use both display() and sides() methods.

    Main Function

    • An instance of a Triangle named myTriangle is created.
    • display() will first access the display() method by calling the Triangle class and then the Shape class because of inheritance.
    • Similarly, sides() will inherit from sides() of the Polygon class,
    • and myTriangle.type() from type() of Triangle class
  • Multiple Inheritance in C++

    Multiple inheritance in C++ is a feature that allows a class to inherit from more than one base class, which means a derived class can have multiple parent classes and inherit attributes and behaviors from all the base classes.

    Implementing Multiple Inheritance

    To implement multiple inheritance, you need to specify multiple base classes in the derived class and declare it using a comma-separated list.

    Syntax

    The syntax of multiple inheritance in C++ is −

    classBase1{// Base class 1 members};classBase2{// Base class 2 members};classDerived:public Base1, public Base2{// Derived class members};

    Block Diagram of Multiple Inheritance

    See the below block diagram demonstrating multiple inheritance −

    C++ Multiple Inheritance

    As per the above diagram, classes “Car” and “Boat” are the base classes and they are deriving over “DualModeVehicle” class in order to implement multiple inheritance.

    Example of Multiple Inheritance

    In the following example, there are two base classes, “Car” and “Boat”, and one derived class, which is “DualModeVehicle”. Both of the base classes are inherited by the derived class.

    #include <iostream>usingnamespace std;// Base class 1classCar{public:voiddrive(){
             cout <<"Driving on land"<< endl;}};// Base class 2classBoat{public:voidsail(){
             cout <<"Sailing on water"<< endl;}};// Derived classclassDualModeVehicle:public Car, public Boat{public:voiduse(){drive();// Calls the drive function from Carsail();// Calls the sail function from Boat}};intmain(){
       DualModeVehicle myVehicle;
       myVehicle.use();// Demonstrates both functionalitiesreturn0;}

    Output

    Driving on land
    Sailing on water
    

    Explanation

    • Class Car is our first base class with public member function drive(), whereas class boat is the second base class with public member function sail().
    • Now a derived class named DualModeVehicle, which inherits from both Car and Boat and uses multiple inheritance to combine the functionalities of both base classes.
    • Where it has a public member function use(), which calls the drive() method from the Car class and the sail() method from the Boat class.

    Main function

    • Now here, an instance of DualModeVehicle, named myVehicle, is created.
    • where the use() method of myVehicle is called, which in turn calls both drive() and sail().
    • returns 0 indicates successful execution.

    Challenges in Multiple Inheritance

    Multiple inheritance in C++ allows a class to inherit from more than one base class which provides flexibility and reusability. However, it also introduces several challenges, discussed below −

    • Ambiguity − When two or more base classes have members with the same name cause ambiguity.
    • Diamond problem − It arises when a class inherits from two classes that both inherit from a common base class which causes ambiguity and conflicts due to multiple copies of the base class, which is ultimately known as the Diamond problem.

    Ambiguity in Multiple Inheritance

    If two or more base classes have members (functions or variables) with the same name, the compiler won’t be able to decide which one to use, which ultimately leads to ambiguity.

    This can be resolved using scope resolution.

    Syntax

    classBase1{public:voidshow(){ cout <<"Base1 show"<< endl;}};classBase2{public:voidshow(){ cout <<"Base2 show"<< endl;}};classDerived:public Base1, public Base2{public:voidshow(){Base1::show();// Explicitly calls Base1's showBase2::show();// Explicitly calls Base2's show}};

    Handling Ambiguity in Multiple Inheritance

    Here we will demonstrate how to handle ambiguity in multiple inheritance by using explicit scope resolution to specify which base class’s method should be called.

    Example

    Lets consider it with an example

    #include <iostream>usingnamespace std;classBase1{public:voidshow(){
             cout <<"Base1 show"<< endl;}};classBase2{public:voidshow(){
             cout <<"Base2 show"<< endl;}};classDerived:public Base1, public Base2{public:voidshow(){// Ambiguity occurs here because both Base1 and Base2 have a show() methodBase1::show();// Explicitly calls Base1's showBase2::show();// Explicitly calls Base2's show}};intmain(){
       Derived obj;
       obj.show();// Calls Derived show() method, which resolves ambiguityreturn0;}

    Output

    Base1 show
    Base2 show
    

    In int main() body, we had called Deriveds show() method, which resolved the ambiguity.

    Diamond Problem in Multiple Inheritance

    A diamond problem in C++ occurs when a class inherits from two classes that both inherit from a common base class, which ultimately creates ambiguity in the inheritance hierarchy as the derived class now has two copies of the common base class, leading to conflicts.

    Example

    #include <iostream>usingnamespace std;classBase{public:voidshow(){
             cout <<"Base show"<< endl;}};classDerived1:public Base{};classDerived2:public Base{};classFinal:public Derived1, public Derived2{};intmain(){
       Final obj;// obj.show(); // This line will cause ambiguityreturn0;}

    Diamond Problem Solution in Multiple Inheritance

    The primary solution for the Diamond Problem in C++ is to use virtual inheritance.

    Example

    #include <iostream>usingnamespace std;classBase{public:voidshow(){
             cout <<"Base show"<< endl;}};classDerived1:virtual public Base{};// Virtual inheritanceclassDerived2:virtual public Base{};// Virtual inheritanceclassFinal:public Derived1, public Derived2{};intmain(){
       Final obj;
       obj.show();// Now this calls Base's show() without ambiguityreturn0;}

    Output

    Base show
    

    By using virtual inheritance, we can avoid the Diamond problem challenge, which ensures that only one instance of the base class exists in the derived class hierarchy.

    Benefits of Using Multiple Inheritance

    • Code reusability, as it allows developers to use existing classes to create new classes with combined functionalities.
    • It models real-world entities more accurately, where a derived class may have characteristics of multiple base classes.
    • It enables a more flexible and modular design.
  • C++ Inheritance

    One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.

    When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

    The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

    Base and Derived Classes

    A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form −

    classderived-class: access-specifier base-class

    Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default.

    Consider a base class Shape and its derived class Rectangle as follows −

    #include <iostream>usingnamespace std;// Base classclassShape{public:voidsetWidth(int w){
             width = w;}voidsetHeight(int h){
             height = h;}protected:int width;int height;};// Derived classclassRectangle:public Shape{public:intgetArea(){return(width * height);}};intmain(void){
       Rectangle Rect;
     
       Rect.setWidth(5);
       Rect.setHeight(7);// Print the area of the object.
       cout <<"Total area: "<< Rect.getArea()<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Total area: 35
    

    Access Control and Inheritance

    A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.

    We can summarize the different access types according to – who can access them in the following way −

    Accesspublicprotectedprivate
    Same classyesyesyes
    Derived classesyesyesno
    Outside classesyesnono

    A derived class inherits all base class methods with the following exceptions −

    • Constructors, destructors and copy constructors of the base class.
    • Overloaded operators of the base class.
    • The friend functions of the base class.

    Type of Inheritance

    When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access-specifier as explained above.

    We hardly use protected or private inheritance, but public inheritance is commonly used. While using different type of inheritance, following rules are applied −

    • Public Inheritance − When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class’s private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
    • Protected Inheritance − When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.
    • Private Inheritance − When deriving from a private base class, public and protected members of the base class become private members of the derived class.

    Multiple Inheritance

    A C++ class can inherit members from more than one class using multiple inheritance. Multiple inheritance is a feature that allows a class to inherit from more than one base class, which means a derived class can have multiple parent classes and inherit attributes and behaviors from all the base classes.

    and here is the extended syntax −

    class derived-class: access baseA, access baseB....
    

    Where access is one of public, protected, or private and would be given for every base class and they will be separated by comma as shown above. Let us try the following example −

    #include <iostream>usingnamespace std;// Base class ShapeclassShape{public:voidsetWidth(int w){
             width = w;}voidsetHeight(int h){
             height = h;}protected:int width;int height;};// Base class PaintCostclassPaintCost{public:intgetCost(int area){return area *70;}};// Derived classclassRectangle:public Shape, public PaintCost{public:intgetArea(){return(width * height);}};intmain(void){
       Rectangle Rect;int area;
     
       Rect.setWidth(5);
       Rect.setHeight(7);
    
       area = Rect.getArea();// Print the area of the object.
       cout <<"Total area: "<< Rect.getArea()<< endl;// Print the total cost of painting
       cout <<"Total paint cost: $"<< Rect.getCost(area)<< endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Total area: 35
    Total paint cost: $2450