How does a subclass copy constructor call a copy constructor of its parent class and a copy constructor call?

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.