Home > Blockchain >  In C , calling a derived constructor creates a base object or not?
In C , calling a derived constructor creates a base object or not?

Time:10-20

#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?

CodePudding user response:

The constructor of Derived uses its first argument (11) to initialize its base class Base, so the member Derived.x has the value 11. This is what is output by d.print().

The constructor of Derived uses its second argument (22) to initialize its member b (whose type is Base). This is what is output by d.b.print().

There are two Base objects here. d is a Derived, which is also a Base. The member d.b is a Base as well.

The argument list of the Derived constructor can be whatever you want it to be, depending on how you want to initialize any of its contents.

CodePudding user response:

The value of i is allocated to the variable x of the class Derived, and the value of j is allocated to the variable x of the object b declared in Derived. The x of Derived and the x of b are two different variables. The second argument is required if you want to allocate a value to b. You can call the constructor for Base explicitly as an alternative to using 2 arguments in the Derived constructor.

  • Related