The Wayback Machine - https://web.archive.org/web/20240930163912/https://www.geeksforgeeks.org/constructor-in-multiple-inheritance-in-cpp/
Open In App

Constructor in Multiple Inheritance in C++

Last Updated : 23 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 constructors of inherited classes are called in the same order in which they are inherited.

Multiple Inheritance Model

Syntax of Multiple Inheritance:

Syntax of Multiple Inheritance:

class S: public A1, virtual A2
{
….
};                                                                                            

Here,
A2(): virtual base constructor
A1(): base constructor
S(): derived constructor

Example 1: Below is the C++ program to show the concept of Constructor in Multiple Inheritance.

C++




// C++ program to implement
// constructor in multiple
// inheritance
#include<iostream>
using namespace std;
class A1
{
  public:
  A1()
  {
    cout << "Constructor of the base class A1 \n";
  }
 
};
 
class A2
{
  public:
  A2()
  {
    cout << "Constructor of the base class A2 \n";
  }
 
};
 
class S: public A1, virtual A2
{
  public:
  S(): A1(), A2()
  {
    cout << "Constructor of the derived class S \n";
  }
};
 
// Driver code
int main()
{
  S obj;
  return 0;
}


Output

Constructor of the base class A2 
Constructor of the base class A1 
Constructor of the derived class S 

Time complexity: O(1)
Auxiliary Space: O(1)

Example 2: Below is the C++ program to show the concept of Constructor in Multiple Inheritance.

C++




// C++ program to implement
// constructors 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;
        }
};
 
// Driver code
int main()
{
    S obj;
    return 0;
}


Output

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

Time complexity: O(1)
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

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
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
Multiple Inheritance in C++
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
5 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
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit from the Object class directly or indirectly. Theref
4 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
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
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
What is conversion constructor in C++?
Pre-requisite: Type Conversion in C++ and Use of explicit keyword in C++ A conversion constructor is a single-parameter constructor that is declared without the function specifier explicitly. The compiler uses conversion constructors to convert objects from the type of the first parameter to the type of the conversion constructor's class. Example:
3 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; class MyClass { vector&lt;int&gt; vec; public: MyClass(vector&lt;int&gt; v) { vec = v; } void print()
2 min read
Constructor Delegation in C++
Sometimes it is useful for a constructor to be able to call another constructor of the same class. This feature, called Constructor Delegation, was introduced in C++ 11.An example program without delegation : C/C++ Code // A C++ program to demonstrate need of // constructor delegation. #include <iostream> using namespace std; class A { int x,
3 min read
Is body of a Default Constructor blank in C++?
The answer to this question depends upon 2 scenarios: Scenario 1: When there is a Virtual function in the program: In this scenario, compiler automatically creates virtual table(known as V-Table) and VVPTR(Virtual Void Pointer). V-Table contains the virtual method calls whereas VVPTR contain the address of virtual methods which are present in V-Tab
2 min read
How to create a List with Constructor in C++ STL
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about doubly linked list. For implementing a singly linked list, we use forward list. A list can be created with the he
2 min read
Dynamic Constructor in C++ with Examples
When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor. By using this, we can dynamically initialize the objects. Example 1: C/C++ Code #include <iostream> using namespace std; class geeks { const char* p; public: // default constructor geeks() { // allocating memo
3 min read
Difference Between Constructor and Destructor in C++
Constructor: A constructor is a member function of a class that has the same name as the class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of the class. It is called whenever an instance of the class is created. It can be defined manually with argument
3 min read
How to Define the Constructor Outside the Class in C++?
A constructor is a special type of member function whose task is to initialize the objects of its class. It has no return type so can't use the return keyword and it is implicitly invoked when the object is created. Constructor is also used to solve the problem of initialization. It is called after the object is created.Same name as of class. Const
2 min read
C++ default constructor | Built-in types for int(), float, double()
A constructor without any arguments or with default values for every argument is treated as the default constructor. C++ allows even built-in types (primitive types) to have default constructors. The function style cast int() is analogous(similar in some way) to casting 0 to the required type.It will be called by the compiler when in need(precisely
2 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 min read
Is it possible to call constructor and destructor explicitly in C++?
A constructor is a special member function that is automatically called by the compiler when an object is created and the destructor is also a special member function that is also implicitly called by the compiler when the object goes out of scope. They are also called when a dynamically allocated object is allocated and destroyed, a new operator a
3 min read
Order of Constructor/ Destructor Call in C++
Prerequisite: Constructors Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class. If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that t
4 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
Can a constructor be private in C++ ?
Prerequisite : Constructors A constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created. By default, constructors are defined in public section of class. So, question is can a constructor be defined in private section of class ? Answer : Ye
3 min read
When is a Copy Constructor Called in C++?
A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object. In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value
2 min read
Parameterized Constructor in C++
In C++, parameterized constructor is a type of constructor that can accept arguments. Parameterized Constructors make it possible to pass arguments to initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the pa
4 min read
When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference). When should we write our own copy constructor?C++ compiler provides a default copy constructor (and assignment operator) with class. When we don't provide an implementation of the copy constructor (and assignm
2 min read