Pass parameter to two base classes : base class « Class « C++ Tutorial






#include <iostream>
using namespace std;

class base1 {
protected:
  int i;
public:
  base1(int x) { 
     i=x; 
     cout << "Constructing base1\n"; 
  }
  ~base1() { 
     cout << "Destructing base1\n"; 
  }
};

class base2 {
protected:
  int k;
public:
  base2(int x) { 
     k=x; 
     cout << "Constructing base2\n"; 
  }
  ~base2() { 
     cout << "Destructing base2\n"; 
  }
};

class derived: public base1, public base2 {
  int j;
public:
  derived(int x, int y, int z): base1(y), base2(z){ 
     j=x; 
     cout << "Constructing derived\n"; 
  }

  ~derived() { 
     cout << "Destructing derived\n"; 
  }
  void show() { 
     cout << i << " " << j << " " << k << "\n"; 
  }
};

int main()
{
  derived ob(3, 4, 5);

  ob.show();

  return 0;
}
Constructing base1
Constructing base2
Constructing derived
4 3 5
Destructing derived
Destructing base2
Destructing base1








9.17.base class
9.17.1.Add a constructor to Base class
9.17.2.Add a overloaded constructor to base class
9.17.3.Call base's default constructor automatically
9.17.4.Call base virtual function explicitly
9.17.5.Virtual base classes
9.17.6.Pass parameter to two base classes