How does a subclass copy constructor call a copy constructor of its parent class and a copy constructor call?
Class base {
Public:
Base (int initialvalue = 0): x (initialvalue ){}
Base (const base & rhs): x (rhs. x ){}
Private:
Int x;
};
Class derived: public base {
Public:
Derived (int initialvalue)
: Base (initialvalue), y (initialvalue ){}
Derived (const derived & rhs) // incorrect copy
: Y (rhs. y) {}// Constructor
Private:
Int y;
};
The derived class shows a bug that occurs in all c ++ environments: When a copy of the derived is created, the basic class is not copied. Of course, the base part of this derived object is still created, but it is created using the default base constructor. The member x is initialized to 0 (the default parameter value of the default constructor ), the x value of the Copied object is ignored!
To avoid this problem, the derived copy constructor must call the base copy constructor instead of the base default constructor. This is easy to do. You only need to specify an initialization value for base in the member initialization list of the copy constructor of derived:
Class derived: public base {
Public:
Derived (const derived & rhs): base (rhs), y (rhs. y ){}
...
};
Now, when an existing object of the same type is used to copy and create a derived object, its base part will also be copied.