简体   繁体   中英

Calling copy constructor of base class while creating object of derive class by copying another object of derive class

class base {};
class der : public base{};


der d1;
der d2(d1);

This statement invokes default constructor of class base then copy constructor of claas der. My question is why C++ has not provided the feature of calling copy constructor of base class while creating object of derive class by copying another object of derive class

Short version

This statement invokes default constructor of class base then copy constructor of claas der.

No, it doesn't.

My question is why C++ has not provided the feature of calling copy constructor of base class while creating object of derive class by copying another object of derive class

It does.


Long(er) version

I don't know how you came to the conclusion that the base default constructor is invoked during the construction of d2 , but it is not. The synthesised base copy constructor is invoked, as you expect.

This is really easy to test :

struct base {
   base() { cout << "*B"; }
   base(base const& b) { cout << "!B"; }
  ~base() { cout << "~B"; }
};

struct der : base {};

int main() {
   der d1;
   der d2(d1);
}

// Output: *B!B~B~B

Copy constructor of the derived class call the default constructor of the base class.

Below sample programs demonstrates the same.

#include <iostream>

using namespace std;

class Base
{
public:
    Base(){ cout<<"Base"<<endl; }
    Base(int i){ cout<<"Base int "<<endl; }
    Base(const Base& obj){ cout<<"Base CC"<<endl; }
};

class Derv : public Base
{
public:
    Derv(){ cout<<"Derv"<<endl; }
    Derv(int i){ cout<<"Derv int "<<endl; }
    Derv(const Derv& obj){ cout<<"Derv CC"<<endl; }
};

int main()
{
    Derv d1 = 2;
    Derv d2 = d1; // Calls the copy constructor

    return 0;
}

This statement invokes default constructor of class base then copy constructor of claas der.

No it does not.

The first line invokes the default construct of class der , which invokes the default constructor of class base . The second line invokes the copy constructor of class der , because you're copying one der instance to another.

The compiler-generated copy-constructor will invoke the copy constructor of the base class.

You have probably added a user-defined copy constructor for der . In such a case you must explicitly invoke the copy constructor of the base class.

der::der(const der& other): base(other), ... {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM