Underlying implementation principle of C ++ virtual functions

Source: Internet
Author: User

Underlying implementation principle of C ++ virtual functions

In C ++, polymorphism is implemented using virtual functions. For example, the following code is available:

#include 
 
  using namespace std;class Animal{public:void Cry(){cout << "Animal cry!" << endl;}};class Dog :public Animal{public:void Cry(){cout << "Wang wang!" << endl;}};void MakeAnimalCry(Animal& animal){animal.Cry();}int main(){Dog dog;dog.Cry();MakeAnimalCry(dog);return 0;}
 

 

The output is as follows:

 

An Animal class is defined here. The Dog class inherits this class and overwrites its Cry method. There is a MakeAnimalCry method that imports an Animal reference and a dog object, but the output is indeed an Animal output. Ideally, if you want to input a dog object, you should call the Cry method of dog. To implement this polymorphism, you must declare Animal: Cry () as a virtual function. You can use the Animal pointer or Animal reference to access Animal objects. This pointer or reference can point to Animal, Dog, or Cat objects without worrying about which objects they point. The modification code is as follows:

#include 
  
   using namespace std;class Animal{public:virtual void Cry(){cout << "Animal cry!" << endl;}};class Dog :public Animal{public:void Cry(){cout << "Wang wang!" << endl;}};class Cat:public Animal{public:void Cry(){cout << "Meow meow" << endl;}};void MakeAnimalCry(Animal& animal){animal.Cry();}int main(){Dog dog;Cat cat;//dog.Cry();MakeAnimalCry(dog);MakeAnimalCry(cat);return 0;}
  

The modified output is as follows:


This isPolymorphismObject of the derived class is treated as a base class object, and the Cry Implementation of the derived class is executed. If the base class Pointer Points to a derived class object, when the operator delete is called using this pointer, that is, for a derived class Object instantiated in the free storage area using new, if a base class pointer is assigned and delete is called through the pointer, The destructor of the derived class is not called. This may cause problems such as unreleased resources and Memory leakage. To avoid this problem, you can declare the destructor of the base classVirtual Functions.

The above program demonstrates the effect of polymorphism, that is, in the MakeAnimalCry function, although the Cry method is called through Animal reference, the actual call is indeed Dog: Cry or Cat :: cry method. In the compilation phase, the compiler does not know the object to be passed to the function, and cannot execute different Cry methods under different circumstances. Which Cry method should be called is clearly determined in the running stage. This is implemented using the multi-state invisible logic, which is provided by the compiler in the compilation phase. The following describes in detail the underlying implementation principles of virtual functions.

For example, the Base class below declares N virtual functions:

Class Base {public: virtual void Func1 () {// implementation code of Func1} virtual void Func2 () {// implementation code of Func2} // virtual void FuncN () {// implementation code of FuncN for virtual functions such as Func3 and Func4 }};

The following Derived class inherits the Base class and covers all other virtual functions except Func2,

Class Derived: public Base {public: virtual void Func1 () {// Func2 overwrite the Func1 code of the Base class} // The implementation code of all other virtual functions except Func2 virtual void FuncN () {// FuncN overwrites the Base class FuncN code }};

After seeing this inheritance hierarchy, the compiler knows that Base defines virtual functions and overwrites these functions in the Derived class. In this case, the compiler createsVirtual Function Table (VFT). That is to say, the Base and Derived classes both have their own virtual function tables. When instantiating objects of these classes, a Hidden Pointer VFT * will be created, which points to the corresponding VFT. VFT can be considered as a static array containing function pointers, with each pointer pointing to the corresponding virtual function. Shows the table of virtual functions of Base and Derived classes:


Each virtual function table consists of function pointers, and each Pointer Points to the implementation of the corresponding virtual function. In the Derived-like virtual function table, all function pointers, except one function pointer, point to the local virtual function implementation. Derived does not overwrite Base: Func2, so the corresponding virtual function pointer points to the implementation of Func2 of the Base class. This means that when the following code is executed, the compiler will find the VFT of the Derived class and make sure to call the implementation of Base: Func2:

Derived objDerived;objDerived.Func2();

This is also true when overwriting methods are called:

void DoSomething(Base& objBase){objBase.Func1();}int main(){Derived objDerived;DoSomething(objDerived);}

In this case, although objDerived is passed to objBase and then interpreted as a Base instance, The VFT pointer of this instance still points to the virtual function table of the Derived class, therefore, the VFT executes the Derived: Func1. virtual function table to realize the C ++ polymorphism through the above method.

It is also very easy to verify the existence of the virtual function table. You can compare the same class, one containing the virtual function, and the other without it. You will know its size.

# Include
   
    
Using namespace std; class Test {public: int a, B; void DoSomething () {}}; class Base {public: int a, B; virtual void DoSomething () {}}; int main () {cout <"sizeof (Test):" <
    
     
The execution output is as follows: although the two classes are almost the same, because the DoSomething method in the Base is a virtual function, the compiler generates a virtual function table for the Base class, and reserved space for its virtual function table pointer. Therefore, the Base class occupies eight more bytes of memory than the Test class.
    
   

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.