The Wayback Machine - https://web.archive.org/web/20241122203325/https://www.geeksforgeeks.org/multiple-inheritance-in-c/
Open In App

Multiple Inheritance in C++

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
 

Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes.  The constructors of inherited classes are called in the same order in which they are inherited. For example, in the following program, B’s constructor is called before A’s constructor.

A class can be derived from more than one base class.

Eg: 

(i) A CHILD class is derived from FATHER and MOTHER class
(ii) A PETROL class is derived from LIQUID and FUEL class.

Syntax:

class A
{
... .. ...
};
class B
{
... .. ...
};
class C: public A,public B
{
... ... ...
};
CPP
#include<iostream>
using namespace std;

class A
{
public:
  A()  { cout << "A's constructor called" << endl; }
};

class B
{
public:
  B()  { cout << "B's constructor called" << endl; }
};

class C: public B, public A  // Note the order
{
public:
  C()  { cout << "C's constructor called" << endl; }
};

int main()
{
    C c;
    return 0;
}

Output:

B's constructor called
A's constructor called
C's constructor called

Multiple inheritance allows a class to inherit from more than one base class. To understand the complexities and implementation of multiple inheritance, the C++ Course covers this topic in detail.

The destructors are called in reverse order of constructors.

The diamond problem The diamond problem occurs when two superclasses of a class have a common base class. For example, in the following diagram, the TA class gets two copies of all attributes of Person class, this causes ambiguities.
For example, consider the following program. 

CPP
#include<iostream>
using namespace std;
class Person {
   // Data members of person 
public:
    Person(int x)  { cout << "Person::Person(int ) called" << endl;   }
};

class Faculty : public Person {
   // data members of Faculty
public:
    Faculty(int x):Person(x)   {
       cout<<"Faculty::Faculty(int ) called"<< endl;
    }
};

class Student : public Person {
   // data members of Student
public:
    Student(int x):Person(x) {
        cout<<"Student::Student(int ) called"<< endl;
    }
};

class TA : public Faculty, public Student  {
public:
    TA(int x):Student(x), Faculty(x)   {
        cout<<"TA::TA(int ) called"<< endl;
    }
};

int main()  {
    TA ta1(30);
}
Person::Person(int ) called
Faculty::Faculty(int ) called
Person::Person(int ) called
Student::Student(int ) called
TA::TA(int ) called

In the above program, constructor of ‘Person’ is called two times. Destructor of ‘Person’ will also be called two times when object ‘ta1’ is destructed. So object ‘ta1’ has two copies of all members of ‘Person’, this causes ambiguities. The solution to this problem is ‘virtual’ keyword. We make the classes ‘Faculty’ and ‘Student’ as virtual base classes to avoid two copies of ‘Person’ in ‘TA’ class.

For example, consider the following program. 

CPP
#include<iostream>
using namespace std;
class Person {
public:
    Person(int x)  { cout << "Person::Person(int ) called" << endl;   }
    Person()     { cout << "Person::Person() called" << endl;   }
};

class Faculty : virtual public Person {
public:
    Faculty(int x):Person(x)   {
       cout<<"Faculty::Faculty(int ) called"<< endl;
    }
};

class Student : virtual public Person {
public:
    Student(int x):Person(x) {
        cout<<"Student::Student(int ) called"<< endl;
    }
};

class TA : public Faculty, public Student  {
public:
    TA(int x):Student(x), Faculty(x)   {
        cout<<"TA::TA(int ) called"<< endl;
    }
};

int main()  {
    TA ta1(30);
}

Output:

Person::Person() called
Faculty::Faculty(int ) called
Student::Student(int ) called
TA::TA(int ) called

In the above program, constructor of ‘Person’ is called once. One important thing to note in the above output is, the default constructor of ‘Person’ is called. When we use ‘virtual’ keyword, the default constructor of grandparent class is called by default even if the parent classes explicitly call parameterized constructor.

How to call the parameterized constructor of the ‘Person’ class?

The constructor has to be called in ‘TA’ class.

For example, see the following program. 

CPP
#include<iostream>
using namespace std;
class Person {
public:
    Person(int x)  { cout << "Person::Person(int ) called" << endl;   }
    Person()     { cout << "Person::Person() called" << endl;   }
};

class Faculty : virtual public Person {
public:
    Faculty(int x):Person(x)   {
       cout<<"Faculty::Faculty(int ) called"<< endl;
    }
};

class Student : virtual public Person {
public:
    Student(int x):Person(x) {
        cout<<"Student::Student(int ) called"<< endl;
    }
};

class TA : public Faculty, public Student  {
public:
    TA(int x):Student(x), Faculty(x), Person(x)   {
        cout<<"TA::TA(int ) called"<< endl;
    }
};

int main()  {
    TA ta1(30);
}

Output:

Person::Person(int ) called
Faculty::Faculty(int ) called
Student::Student(int ) called
TA::TA(int ) called

In general, it is not allowed to call the grandparent’s constructor directly, it has to be called through parent class. It is allowed only when ‘virtual’ keyword is used.

As an exercise, predict the output of following programs.

Question 1 

CPP
#include<iostream>
using namespace std;

class A
{
  int x;
public:
  void setX(int i) {x = i;}
  void print() { cout << x; }
};

class B:  public A
{
public:
  B()  { setX(10); }
};

class C:  public A  
{
public:
  C()  { setX(20); }
};

class D: public B, public C {
};

int main()
{
    D d;
    d.print();
    return 0;
}


Question 2 

CPP
#include<iostream>
using namespace std;

class A
{
  int x;
public:
  A(int i) { x = i; }
  void print() { cout << x; }
};

class B: virtual public A
{
public:
  B():A(10) {  }
};

class C:  virtual public A 
{
public:
  C():A(10) {  }
};

class D: public B, public C {
};

int main()
{
    D d;
    d.print();
    return 0;
}




Previous Article
Next Article

Similar Reads

Java and Multiple Inheritance
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which
6 min read
Difference between Single and Multiple Inheritance in C++
Single InheritanceSingle inheritance is one in which the derived class inherits the single base class either public, private, or protected access specifier. In single inheritance, the derived class uses the features or members of the single base class. These base class members can be accessed by a derived class or child class according to the acces
4 min read
Constructor in Multiple Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The construct
2 min read
OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
We have discussed following topics on Object Oriented Programming in Python Object Oriented Programming in Python | set-1 Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing) In this article, Inheritance is introduced. One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanis
4 min read
C++ | Inheritance | Question 1
#include<iostream> using namespace std; class Base1 { public: Base1() { cout << " Base1's constructor called" << endl; } }; class Base2 { public: Base2() { cout << "Base2's constructor called" << endl; } }; class Derived: public Base1, public Base2 { public: Derived() { cout << "Derived's
1 min read
C++ | Inheritance | Question 2
Output? #include <iostream> using namespace std; class Base1 { public: ~Base1() { cout << " Base1's destructor" << endl; } }; class Base2 { public: ~Base2() { cout << " Base2's destructor" << endl; } }; class Derived: public Base1, public Base2 { public: ~Derived() { cout << " Derived's d
1 min read
C++ | Inheritance | Question 3
Assume that an integer takes 4 bytes and there is no alignment in following classes, predict the output. #include<iostream> using namespace std; class base { int arr[10]; }; class b1: public base { }; class b2: public base { }; class derived: public b1, public b2 {}; int main(void) { cout << sizeof(derived); return 0; } (A) 40 (B) 80 (C
1 min read
C++ | Inheritance | Question 4
#include<iostream> using namespace std; class P { public: void print() { cout <<" Inside P"; } }; class Q : public P { public: void print() { cout <<" Inside Q"; } }; class R: public Q { }; int main(void) { R r; r.print(); return 0; } (A) Inside P (B) Inside Q (C) Compiler Error: Ambiguous call to print() Answe
1 min read
C++ | Inheritance | Question 5
Output? #include<iostream> using namespace std; class Base { private: int i, j; public: Base(int _i = 0, int _j = 0): i(_i), j(_j) { } }; class Derived: public Base { public: void show(){ cout<<" i = "<<i<<" j = "<<j; } }; int main(void) { Derived d; d.show(); return 0; } (A) i = 0 j = 0 (B) Compile
1 min read
C++ | Inheritance | Question 6
#include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Base *bp = new Derived; Derived *dp = new Base; } (A) No Compiler Error (B) Compiler Error in line "Base *bp = new Derived;" (C) Compiler Error in line " Derived *dp = new Base;" (D) Runtime Error Answer: (C) Explanation: A Base class pointer/re
1 min read
C++ | Inheritance | Question 7
#include<iostream> using namespace std; class Base { public: void show() { cout<<" In Base "; } }; class Derived: public Base { public: int x; void show() { cout<<"In Derived "; } Derived() { x = 10; } }; int main(void) { Base *bp, b; Derived d; bp = &d; bp->show(); cout << bp->x; return 0; } (A
1 min read
C++ | Inheritance | Question 8
C/C++ Code #include using namespace std; class Base { public: int fun() { cout (A) Base::fun(int i) called (B) Derived::fun() called (C) Base::fun() called (D) Compiler Error Answer: (D)Explanation: If a derived class writes its own method, then all functions of base class with same name become hidden, even if signatures of base class functions are
1 min read
C++ | Inheritance | Question 10
Output of following program? C/C++ Code #include #include using namespace std; class Base { public: virtual string print() const { return \"This is Base class\"; } }; class Derived : public Base { public: virtual string print() const { return \"This is Derived class\"; } }; void describe(Base p) { cout (A)This is Derived class This is Base class (B
1 min read
C++ | Inheritance | Question 11
#include<iostream> using namespace std; class Base { public : int x, y; public: Base(int i, int j){ x = i; y = j; } }; class Derived : public Base { public: Derived(int i, int j):x(i), y(j) {} void print() {cout << x <<" "<< y; } }; int main(void) { Derived q(10, 10); q.print(); return 0; } (A) 10 10 (B) Compiler E
1 min read
C++ | Inheritance | Question 12
#include<iostream> using namespace std; class Base { protected: int a; public: Base() {a = 0;} }; class Derived1: public Base { public: int c; }; class Derived2: public Base { public: int c; }; class DerivedDerived: public Derived1, public Derived2 { public: void show() { cout << a; } }; int main(void) { DerivedDerived d; d.show(); retu
2 min read
C++ | Inheritance | Question 13
#include<iostream> using namespace std; class Base1 { public: char c; }; class Base2 { public: int c; }; class Derived: public Base1, public Base2 { public: void show() { cout << c; } }; int main(void) { Derived d; d.show(); return 0; } (A) Compiler Error in "cout << c;" (B) Garbage Value (C) Compiler Error in "class Derived:
1 min read
C++ | Inheritance | Question 14
Consider the below C++ program. #include<iostream> using namespace std; class A { public: A(){ cout <<"1";} A(const A &obj){ cout <<"2";} }; class B: virtual A { public: B(){cout <<"3";} B(const B & obj){cout<<"4";} }; class C: virtual A { public: C(){cout<<"5
1 min read
Constructor in Multilevel Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multilevel Inheritance Derivation of a class from another derived class is called Multilevel Inheritance. Class A is the base class for the d
2 min read
Inheritance Ambiguity in C++
Pre-requisites: Inheritance in C++, Multiple Inheritance in C++ In multiple inheritances, when one class is derived from two or more base classes then there may be a possibility that the base classes have functions with the same name, and the derived class may not have functions with that name as those of its base classes. If the derived class obje
6 min read
C++ Multilevel Inheritance
Multilevel Inheritance in C++ is the process of deriving a class from another derived class. When one class inherits another class it is further inherited by another class. It is known as multi-level inheritance. For example, if we take Grandfather as a base class then Father is the derived class that has features of Grandfather and then Child is t
2 min read
C++ Hierarchical Inheritance
Inheritance is a feature of Object-Oriented-programming in which a derived class (child class) inherits the property (data member and member functions) of the Base class (parent class). For example, a child inherits the traits of their parents. In Hierarchical inheritance, more than one sub-class inherits the property of a single base class. There
4 min read
Hybrid Inheritance In C++
Before jumping into Hybrid Inheritance, let us first know what is inheritance. Inheritance is a fundamental OOP concept in C++ that allows a new class, also known as a subclass or derived class, to inherit properties and methods from an already-existing class, also known as a superclass or base class. C++ supports 5 types of inheritance: Single Inh
6 min read
Inheritance and Friendship in C++
Inheritance in C++: This is an OOPS concept. It allows creating classes that are derived from other classes so that they automatically include some of the functionality of its base class and some functionality of its own. (See this article for reference) Friendship in C++: Usually, private and protected members of a class cannot be accessed from ou
2 min read
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized constructor in order to initialize some attributes
3 min read
C++ Inheritance Access
Prerequisites: Class-Object in C++Inheritance in C++Before learning about Inheritance Access we need to know about access specifiers. There are three Access specifiers in C++. These are: public - members are accessible from outside the class, and members can be accessed from anywhere.private - members cannot be accessed (or viewed) from outside the
4 min read
Difference between Inheritance and Polymorphism
Inheritance is one in which a new class is created that inherits the properties of the already exist class. It supports the concept of code reusability and reduces the length of the code in object-oriented programming. Types of Inheritance are:Single inheritanceMulti-level inheritanceMultiple inheritancesHybrid inheritanceHierarchical inheritanceEx
5 min read
Does overloading work with Inheritance?
If we have a function in base class and another function with the same name in derived class, can the base class function be called from derived class object? This is an interesting question and as an experiment, predict the output of the following C++ program: [GFGTABS] C++ #include <iostream> using namespace std; class Base { public: int f(
5 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
How can I return multiple values from a function?
We all know that a function in C can return only one value. So how do we achieve the purpose of returning multiple values. Well, first take a look at the declaration of a function. int foo(int arg1, int arg2); So we can notice here that our interface to the function is through arguments and return value only. (Unless we talk about modifying the glo
2 min read
Assigning multiple characters in an int in C language
Consider the following C program. #include <stdio.h> int main(void) { int a = 'd'; printf("%d\n", a); /*OUTPUT - 100 (ASCII Code for character d)*/ int b = 'dd'; printf("%d", b); /*OUTPUT - 25700 (Explanation in detail given below)*/ return 0; } Output : 100 25700 We can easily guess that the output for 'd' is 100 as 100 i
1 min read
Practice Tags :
three90RightbarBannerImg