Virtualize constructors and non-member functions"

Source: Internet
Author: User

Virtual constructor, which seems to be an intuitive violation, because when you have an object pointer or reference, you can use the dynamic type of the object to call virtual functions. In this case, your object has not been constructed yet.

In fact, "virtual constructor" does not declare your constructor as virtual, but a function that determines the type of object to be constructed based on its input data. For example, if you want to read some data from a file or network, you can determine the type of object you want to create from the data.


For example:

The following inheritance system: [from more than tive C ++ p124]

Class base

{

Public:...; // The definition details of the class are not important.

};

Class Child1: public Base

{

Public:... // same as above

};

Class child2: public Base

{

Pubic:... // same as above

};

Class children

{

PRIVATE:

List <base *> Childs;

};

The above children object may be constructed based on the read data (such as the standard input), so the following constructor will be available:

Children: Children (istream & in)

{

While (in is not empty)

// Read the data for initialization and add it to the childs linked list.

}

As a result, we can use a function to read the input stream, construct the object, and return the data during the initialization process. The children class will look like this:

Class children

{

Public:

...

PRIVATE:

Static base * read_input (istream & in );

};

Childrent: Children (istream & in)

{

While (in is not empty)

{

Childs. push_back (read_input (in ));

}

}

In this way, the Ctor is virtualized.


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.