Effective C + + clause 12

Source: Internet
Author: User

When copying an object, do not forget its every ingredient

The author of this section reminds us that in the case of multiple inheritance of the copy or copy assignment operator=, it is important to consider the initialization of the base class partial data.

Compare the code:

Class cutsomer{...Private:stringNamestringTelphone;}; Class Prioritycustomer: Publiccutsomer{ Public:Prioritycustomer() {cout<<"Prioritycustomer Ctor"<<endl; } prioritycustomer (Constprioritycustomer& RHS):p riority (rhs.priority) {cout<<"Prioritycustomer Copy Ctor"<<endl; } prioritycustomer&operator=(Constprioritycustomer& RHS) {cout<<"Prioritycustomer Assign Operator"<<endl; priority=rhs.priority;return* This; }Private:intpriority;};

The data in Prioritycustomer has the following

    int priority;    string name;    string telphone;

While the real copy or copy assignment only deal with the INT priority;
We can see that the above code ignores the processing of the data in the base class section, when the code is modified as follows:

PriorityCustomer(const PriorityCustomer& rhs)        :Cutsomer(rhs),priority(rhs.priority)    {        cout<<"PriorityCustomer Copy Ctor"<<endl;    }    operator=(const PriorityCustomer& rhs)    {        cout<<"PriorityCustomer assign operator"<<endl;        Cutsomer::operator=(rhs);        priority=rhs.priority;        return *this;    }

Effective C + + clause 12

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.