MOREEFFECTIVEC++ITEM35 clause 25 constructor and Non-member functions are virtualized

Source: Internet
Author: User

1.virtual Constructor

A constructor cannot be declared as a virtual function, and a virtual function is used to implement a "type-dependent behavior", that is, to invoke a different entity based on a pointer or a dynamic type that references the object being bound. Now involved in the

Virtual-constructor is actually "imitation virtual-constructor."

Suppose you design a software to handle news events, which are made up of text and graphics

classnlcomponent {//for newsletter components Public://the abstract base class...//contains at least one pure virtual function};classTextBlock: Publicnlcomponent { Public:... //does not contain pure virtual functions};classGraphic: Publicnlcomponent { Public:... //does not contain pure virtual functions};classNewsLetter {//a Newsletter Object Public://by the Nlcomponent object...//the list of linked lists is composedPrivate: List<NLComponent*>Components ;};

These classes are related to each other as

Newsletter may be stored on disk, in order to read the newsletter object from disk into memory, it may have a constructor that accepts the istream& parameter:

class  NewsLetter {public: NewsLetter (IStream& str); ...}; // The pseudo-code for this constructor is this: Newsletter::newsletter (istream& str) {   while (str) {  // Read Next com from str    Ponent object;  // Add the object to the list of newsletter's components; }}

NewsLetter (istream& str) can also be implemented by a readcompnent function with its main function:

classNewsLetter { Public: NewsLetter (IStream&str); ...Private:    //reads the next nlcompnent data from STR, produces the component (Compnent), and returns a pointer to it    Staticnlcompnent* Readcompnent (istream&str); List<NLCompnent*>compnents; ...}; Newsletter::newsletter (IStream&str) {     while(str) {//Adds a pointer returned by readcompnent to the compnents list endcompnents.push_back (readcompnent (str)); }}

The function readcompnent produces a new Nlcompnent subclass object (TextBlock or graphic) and returns a nlcompnent pointer, because it can produce different types of objects, so it is called a virtual Constructor. Virtual constructor is useful in many cases, one of which is to read object information from a disk (or network or tape).

2.virtual copy Constructor

A special virtual Constructor--copy virtual constructor that returns a pointer to a new copy of its caller, and the dynamic type of the pointer is determined by the type of the object that called it. TextBlock and graphic's copy of virtual constructor can look like this:

classnlcomponent { Public:    //statement Virtual copy constructor    VirtualNlcomponent * Clone ()Const=0; ...};classTextBlock: Publicnlcomponent { Public:    VirtualTextBlock * Clone ()Const //Virtual copy Constructor{return NewTextBlock (* This); }    ...};classGraphic: Publicnlcomponent { Public:    VirtualGraphic * Clone ()Const //Virtual copy Constructor{return NewGraphic (* This); }     ...};

So clone is actually the implementation of virtual copy constructor

Although the derived class redefined the virtual function of the base class, the declaration returns a worthwhile type (the parent class returns a pointer or reference, which in the derived class also returns a pointer or reference) must be the same as the base class, but if the function return type is a pointer to base class ( or reference), then derived class can return a pointer (or reference) to its derived class. Therefore, although the above clone is a virtual function, the type of pointer returned can be different

Below we implement the newsletter implementation (normal) copy constructor:

classNewsLetter { Public: NewsLetter (Constnewsletter&RHS); ...Private: List<NLComponent*>Components ;}; Newsletter::newsletter (Constnewsletter&RHS) {    //iterate through the list of RHS, using the virtual copy constructor of each element to copy the element to the Compnents list of this object.     for(List<nlcomponent*>::const_iterator it =rhs.components.begin (); It! = Rhs.components.end (); + +it)//it points to the current element of rhs.compnents, calls the element's clone function to get a copy and adds to the end of the Compnents list of this objectComponents.push_back ((*it)clone ());}

The behavior of 3.non-member Functions

Just as constructors cannot be falsified, the Non-member function cannot be falsified in principle-it is not even a member function. Consider implementing the << operator for TextBlock and graphic to make << To TextBlock and graphic to achieve different behavior, the direct idea is to be <<, but in fact this can not achieve:<< the first operand is ostream&, that is to say << as member function, you can only become a member of the Ostream class, but this is not possible. So << can only be used for non-member functions, which can be taken with virtual constructor similar strategies implemented by virtual Non-member function

classnlcomponent { Public:    Virtualostream& print (ostream& s)Const=0; ...};classTextBlock: Publicnlcomponent {bbs.theithome.com Public:    Virtualostream& print (ostream& s)Const; ...};classGraphic: Publicnlcomponent { Public:    Virtualostream& print (ostream& s)Const; ...}; Inline Ostream&operator<< (ostream& S,Constnlcomponent&c) {    returnC.print (s);}

Summary:

Constructor Virtualization: You can use copy constructors to simulate the construction of different objects by returning pointers to different derived classes.

The virtualization of a function without member variables: Use a virtual function to encapsulate the function that you want to blur.

MOREEFFECTIVEC++ITEM35 clause 25 constructor and Non-member functions are 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.