Inheritance
You can pass Constructor argument objects from
a Derived class constructor to a Base class
constructor
#include
class Base
{
protected:
int base_data_x;
public:
Base() : base_data_x (0) {
cout << "Base - Zero argument Constructor called : " <<
base_data_x << endl;
}
Base(int i): base_data_x(i) {
cout << "Base - One argument Constructor called : " <<
base_data_x << endl;
}
~Base() { cout << "Base destructor called" << endl << endl; }
int Get() { return base_data_x;}
};
class Derived: public Base
{
protected:
int derived_data_x;
public:
Derived() {
cout << "Derived - Zero argument constructor called at
address: "
<< &derived_data_x << " the value is: " <<
derived_data_x << endl;
}
Derived(int i): Base(i), derived_data_x(i) {
cout << "Derived - One argument constructor called: "
<< derived_data_x << endl;
}
~Derived() { cout << "Derived class destructor called" << endl; }
};
void main() {
Derived D;
cout << "Derived - Zero argument constructor, Get() returns: "
<< D.Get() << endl << endl;
Derived D_1(100);
cout << "Derived - One argument constructor, Get() returns : "
<< D_1.Get() << endl << endl;
}
/*
Base - Zero argument Constructor called : 0
Derived - Zero argument constructor called at address: 0x0064FDE0 the
value is:
4203104
Derived - Zero argument constructor, Get() returns: 0
Base - One argument Constructor called : 100
Derived - One argument constructor called: 100
Derived - One argument constructor, Get() returns : 100
Derived class destructor called
Base destructor called
Derived class destructor called
Base destructor called
Press any key to continue
*/
Go Back to Inheritance