Parameters-From Derived To Base Constructor
Parameters can be passed on to base class constructors from derived
constructors. Given a base class
BaseClass and
a class derived from it
DerivedClass:
class DerivedClass: public BaseClass{};
by declaring the constructor of DerivedClass as:
DerivedClass(string s2, string s3):BaseClass(s3){}
one specifies that the second parameter must be passed to the BaseClass constructor.
For classes derived by multiple bases, the method to pass parameters to the
bases is the same.
The typical statement might look like:
DerivedClass(string s2, string s3, int a, int b):BaseClass(s3),BaseClass1(a,b)
Example
#include <iostream>
#include <string>
using namespace std;
class BaseClass
{
string b;
public:
BaseClass(string s1)
{
b = s1;
cout << "BaseClass constructor\n";
}
~BaseClass()
{
cout << "BaseClass destructor\n";
}
};
class DerivedClass: public BaseClass //
{
string d;
public:
DerivedClass(string s2, string s3):BaseClass(s3) // the
// base constructor uses s3
{
d = s2;
cout << "DerivedClass constructor\n";
}
~DerivedClass()
{
cout << "DerivedClass destructor\n";
}
};
int main()
{
DerivedClass d("hi" , "hello");
}
Output
BaseClass constructor
DerivedClass constructor
DerivedClass destructor
BaseClass destructor