C ++ trap: Polymorphism in Constructor

Source: Internet
Author: User

In C ++, the virtual keyword is added to the function to realize polymorphism. Polymorphism can be used to change the implementation of an interface. It is also a means of embedding application-layer code to the underlying implementation. Even if you don't use the Complex C ++ technologies, polymorphism will certainly be used.

However, adding virtual does not necessarily guarantee the success of polymorphism:

# Include <stdio. h>

Class Base {
Public:
Base (){
Init ();
}

Virtual ~ Base (){
Release ();
}

Virtual void Init (){
Printf ("Base: Init \ n ");
}

Virtual void Release (){
Printf ("Base: Release \ n ");
}
};

Class Derived: public Base {
Public:
Virtual void Init (){
Printf ("Derived: Init \ n ");
}

Virtual void Release (){
Printf ("Derived: Release \ n ");
}
};

Int main ()
{
Base * obj = new Derived ();
Delete obj;
Return 0;
}
When a virtual function is called in the constructor, including the destructor, the expected polymorphism cannot be completed. The output result of the above Code is:

Base: Init
Base: Release
From the perspective of language design, I personally do not accept such behavior. I think almost all features of a language should be the same, and such "exceptions" should not or should be minimized. What is the difference between constructing an object in different ways and changing its behavior? (From this sentence, there seems to be a difference)

Of course, from the perspective of language implementation, such running results seem inevitable. Because the construction of the base class is earlier than that of the derived class (as part of it). Only after the derived class is constructed can the virtual table that supports polymorphism be correctly constructed. That is to say, when a virtual function is called in the base class, since the virtual table is correctly constructed, the virtual function of the derived class will not be called. According to the order of the structure, the Destructor will also face the same situation.

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.