Effective C + + clause nine or 10 never call the virtual function during construction and destruction | Make operator= return a reference to *this

Source: Internet
Author: User

1. When a constructor is called in a subclass, its parent constructor is definitely called first. If there is a virtual function in the parent class constructor, and there is a subclass, it must execute the virtual function in the parent class, and the member variable in the subclass is not initialized, so the corresponding function of the subclass cannot be called. That is, the pointer to the virtual function table vptr is not initialized and how to invoke the virtual function of the derived class? The destructor is the same, the derived class is destroyed before the base class, and how to find the corresponding virtual function of the derived class?

2. Practice: Change a function of a subclass to Non-virtual, and then pass the parameter to the parent class function in the child class constructor. The constructor of the parent class can then safely invoke the non-virtual.

Remember:

Do not call the virtual function during construction and destruction, because such calls do not fall to the subclass level.

For assignment operators, we often have to achieve this similar effect, that is, continuous assignment:
int x, y, Z;
x = y = z = 15; The chain reaction of the assignment

x = (y = (z = 15));//execution order

In order to implement the chain assignment above, the assignment operator must return a reference to the left argument of the operator.

Widgets & operator = (const widget& RHS)//return type is a reference

{

return *this; Return to left Object

}

Remember:

The assignment operator returns a reference to *this;

Related Article

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.