简体   繁体   中英

Why passing derived class type as parameter when calling base class copy constructor (C++)?

Regarding when call copy constructor of base class, we have the form:

DerivedClass ( const DerivedClass& obj ) : BaseClass ( obj ) 
{ 
// ... 
} 

I just do not understand why we pass object of derived class to the base class copy constructor.

What else would you want to pass? Because the only other option is a magical pony conjured up from the air.

It's a typical "real type hidden behind a reference to parent" thing. Base class' copy ctor has signature base(const base&) . It doesn't care if you pass a most derived type, or semi derived type, or maybe base type. It only sees the portion it cares about, which is base , and nothing else, so it can do its job properly.

Of course that only works for types derived using public inheritance, which forms is-a relationship between the two.

It looks like the reference to the derived class object is being passed, but in fact it will be implicitly upcasted and that will yield a reference to the base class subobject.

Effectively the code you cite is completely equivalent to this code:

DerivedClass ( const DerivedClass& obj ) :
    BaseClass ( static_cast<const BaseClass&>( obj ) )
{ 
// ...

and the latter code is perfectly reasonable - it invokes the base class subobject constructor by passing it a reference to the base subobject of the already constructed other object.

Object of derived class has "properties of derived class" + "properties of base class"

When we want to create a copy of derived class, we call copy constructor of derived class. Essentially we want to copy "properties of derived class" + "properties of base class" to the new object.

Copy of derived class properties is taken care by derived class copy constructor. To copy properties of base class, we need to explicitly call base class copy constructor.

If you didn't, what would the base class copy from?

A DerivedClass is a BaseClass , so it can be implicitly casted to a reference to a BaseClass and used in the BaseClass copy constructor to copy from.

So BaseClass(const BaseClass&) takes care of copying the members of BaseClass and DerivedClass(const DerivedClass&) takes care of copying the members of DerivedClass .

Doing it this way lets you avoid duplicating the copying-code that is in the BaseClass copy constructor in every class that derives from it, and avoid breakage when the base class is modified.

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