简体   繁体   中英

c++ constructor pass a reference to a base class object

I'm trying to understand copy constructors. In the constructor definition below, the class DataModel is dervived from ComputationModel .

My queston is, when you pass a reference to a base class to a constructor of a derived class is this a copy constructor?

Why would the default copy constructor not be sufficent here?

class DataModel : public ComputationModel {
    public:
      DataModel(const ComputationalModel &other);

      //..
};

mv::DataModel::DataModel(const ComputationModel &other) :
    ComputationModel(other)
{}

Technically, you are able to define a copy constructor of DataModel taking a ComputationalModel reference as a function parameter.

DataModel d1(/* Parameter... */);
ComputationModel c1(/* Parameter... */);

DataModel d2(d1); // copy-construct instance, d1 passed as refence to the base class
DataModel d3(c1); // same behavior

This will, however, almost never be a good idea, because copy-construction of an object typically requires the state of the object to copy from. When you pass a base class reference, you drop all data members of the derived class instance, which leaves the newly created object in a state that is hard to guess from client code.

The default copy constructor has a const-qualified reference argument to the exact same type, in your case:

DataModel(const DataModel& other) = default;

which brings me to your last question

Why would the default copy constructor not be sufficent here?

This is hard to tell without seeing the rest of your inheritance hierarchy. A guideline would be: if the copy constructor of all data members in the hierarchy do the right thing, then a defaulted copy constructor does the right thing as well.

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