Are subclass copy constructor will call the copy constructor of the parent class?

Disclaimer: This article is a blogger original article, welcome to reprint, please indicate the source. https://blog.csdn.net/Think88666/article/details/91639448

Sometimes we habitually think when a subclass copy constructor automatically calls the copy constructor of the parent class , this view comes from the will automatically call the constructor of the parent class when the subclass constructor (parent class before the subclass constructor) , subclass when the destructor will automatically call the parent class destructor (parent after subclass destructor).

But actually a subclass copy constructor not automatically call the parent class copy constructor - thereby causing a problem of missing class data base

code show as below

class Base
{
public:
    Base() {}
    Base(const Base&b)
    {
        cout << "copy construct" << endl;
    }
private:
    int a;
};

class Driver :public Base 
{
public:
    Driver() {}
    Driver(const Driver&dv)
    {
        cout << "Driver Copy construct" << endl;
    }
};
int main()
{
    Driver d1;
    Driver d2 = d1;
    return 0;
}

But in reality at the time of assignment to d2, it calls the copy constructor Driver, then do not call the copy constructor of Base, but will call the default constructor of Base.

How should I do?

class Driver :public Base 
{
public:
    Driver() {}
    Driver(const Driver&dv):Base(dv)
    {
        cout << "Driver Copy construct" << endl;
    }
};

Display configured to call the parent class initialization copy copy constructor parameter list of Driver

Guess you like

Origin blog.csdn.net/Think88666/article/details/91639448