"Virtual" constructor with return values in C ++

Source: Internet
Author: User

How can c ++ have "virtual Constructor "? What is the return value? Sometimes we want the class constructor to be used like other common member functions: override ). We can design such a constructor function:

We define such a "virtual constructor with returned values" in the LB class ". In a derived class, we can overwrite it. Now we can use this constructor like a common member function (in fact, it is a common member function ). Note that override in C ++ must meet the following two conditions:

  1. Only when the return type is variable, but the function signature is variable, that is, the function name and parameter table are variable.
  2. The return type can only be changed from the base class pointer type to the pointer type of the derived class, or from the base class reference type to the reference type of the derived class.

This feature is called "covariant return types )".

The following is a copy constructor ":

Here, we need to pay special attention to the fact that the "Constructor" directly returns a bare right-value pair like pointer or reference, allocating additional heap space. The caller needs to explicitly call the delete operator to analyze the structure after use. We hope to make it more like a real constructor in use, and the generated object will be parsed by the system when it leaves the scope. Otherwise, there will be potential risks. A feasible method is to encapsulate it with a smart pointer, such as the STD: auto_ptr class, which can be safely used. The following code:

Of course, there are advantages and disadvantages in everything. The biggest problem with the use of "virtual constructor" is that in a derived class, it can be overwritten every time ...... This is sometimes annoying ...... It not only increases the amount of code, but also the amount of testing ......

Refer:

Why cannot a constructor be a virtual function?

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.