Multiple choice

What will be the output of the above code?

class base1 {
 public:
  base1() { cout <<\nBase 1 Constructor; }
  ~base1() { cout <<\nBase 1 Destructor; }
};

class base2 {
 public:
  base2() { cout << "\nBase 2 Constructor"; }
  ~base2() { cout <<\nBase 2 Destructor; }
};
class derived : public base1, public base2 {
 public:
  derived() { cout <<\nDerived class Constructor; }
  ~derived() { cout <<\nDerived class Destructor; }
};

  1. Base 1 Constructor Base 1 Destructor Base 2 Constructor Base 2 Destructor Derived class Constructor Derived class Destructor

  2. Derived class ConstructorDerived class DestructorBase 2 ConstructorBase 2 DestructorBase 1 ConstructorBase 1 Destructor

  3. Derived class ConstructorBase 2 ConstructorBase 1 ConstructorBase 1 DestructorBase 2 DestructorDerived class Destructor

  4. Base 1 Constructor Base 2 Constructor Derived class Constructor Derived class Destructor Base 2 Destructor Base 1 Destructor

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

During inheritance, the order of constructor invocation is from parent to child and the destructor is called from child to parent. In case of mulitple inheritance, the constructors are called in order of inheritance. The base class 1 constructor will be invoked first followed by the constructor of the base 2 class, the derived class constuctor will be the last constructor to be called. The destructors will be called in the reverse order of constructors. Their order will be derived from base2->base1.