Implementation principle of Polymorphism

Source: Internet
Author: User

A: What is the principle of polymorphism in C ++?


Q: It is implemented through the late binding technology.

The implementation principle is as follows:

1. The function in the base class contains the virtual keyword, indicating that the method is a virtual function.

2. Subclass inherits the base class, and virtual functions can be overwritten ).

3. the compiler creates a virtual table vtable for each class containing virtual functions.

4. If the child class overrides the parent class virtual function, the Child class virtual table stores the rewrite function entry address.

5. the compiler provides a virtual table pointer vptr for each Class Object), pointing to the virtual table of the class to which the object belongs.

6. When the subclass object is instantiated, the base class constructor is called first, and vptr refers to the base class vtable.

7. The subclass object calls its own constructor after instantiating the base class constructor. If the virtual function is rewritten, vptr points to the subclass vtable. Otherwise, it will not change.

8. Pointing a base class pointer to a subclass object does not affect the pointing of vptr.


References:

1. Implementation principle of C ++ polymorphism, CSDN.

2. Implementation principle of polymorphism in C ++, Cnblogs.



This article from the "one text one ask one world" blog, please be sure to keep this source http://worldinwords.blog.51cto.com/7889522/1293947

Related Article

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.