#include<iostream>
using namespace std;
class Base{
private:
int x;
public:
Base(int i){
x = i;
}
void print(){
cout<<x<<endl;
}
};
class Derived: public Base{
public:
Base b;
public:
//the constructor of the derived class which contains the argument list of base class and the b
Derived(int i, int j): Base(i), b(j)
{}
};
int main(){
Derived d(11, 22);
d.print();
d.b.print();
return 0;
}
Why is the value of b.x 11, but the value of d.b.x is 22?
If the constructor of the base class initializes the int x in class Base, does a Base object exist?
In the argument list of the derived constructor, should there be one argument or two arguments when there is a Base b as a class member?
The constructor of
Deriveduses its first argument (11) to initialize its base classBase, so the memberDerived.xhas the value 11. This is what is output byd.print().The constructor of
Deriveduses its second argument (22) to initialize its memberb(whose type isBase). This is what is output byd.b.print().There are two
Baseobjects here.dis aDerived, which is also aBase. The memberd.bis aBaseas well.The argument list of the
Derivedconstructor can be whatever you want it to be, depending on how you want to initialize any of its contents.