Constructor In Multiple Inheritance in C++

Published: (December 24, 2025 at 02:43 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Constructor

A constructor is a class member function with the same name as the class. Its main job is to initialize class objects. The constructor is automatically called when an object is created.

Multiple Inheritance

Multiple inheritance is a feature of C++ where a class can derive from two or more base classes. The constructors of the base classes are called in the order in which they appear in the inheritance list.

Syntax of Multiple Inheritance

class S : public A1, virtual A2

Example 1

Below is a C++ program that demonstrates constructors in multiple inheritance.

// C++ program to implement constructor in multiple inheritance
#include <iostream>
using namespace std;

class A1 {
public:
    A1() {
        int a = 20, b = 35, c;
        c = a + b;
        cout << "Sum is: " << c << endl;
    }
};

class A2 {
public:
    A2() {
        int x = 50, y = 42, z;
        z = x - y;
        cout << "Difference is: " << z << endl;
    }
};

class S : public A1, virtual A2 {
public:
    S() : A1(), A2() {
        int r = 40, s = 8, t;
        t = r * s;
        cout << "Product is: " << t << endl;
    }
};

int main() {
    S obj;
    return 0;
}

Output

Difference is: 8
Sum is: 55
Product is: 320

Complexity Analysis

  • Time complexity: O(1)
  • Auxiliary space: O(1)
Back to Blog

Related posts

Read more »