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