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:
- Only when the return type is variable, but the function signature is variable, that is, the function name and parameter table are variable.
- 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?