Describe the memory allocation mechanism of virtual functions in C++

  • 2020-11-03 22:32:36
  • OfStack

Because the address translation of a virtual function depends on the memory address of the object, not on the data type (compiler versus function)

The validity check of the call depends on the data type. Originally, if a virtual function is defined in a class, the class and its derived classes

A table of virtual functions, vtable, is generated. Store 1 entry of the vtable in the object address space of the class,

Accounting for 4 bytes, this entry address is in the construct object that is written by the compiler.

The C++ program is as follows:


//#include<stdio.h>

#include<iostream>
using namespace std;

class CMem	
{
	
public:
 CMem(){}
public:
 int m_first;
private:
 unsigned char m_second;
 
public :
 void fun1();
 virtual int funOver(){return 1;}
 
};



class CMemSub : public CMem
{

public:
 CMemSub(){}

public:
 int m_three;

private:
 int m_four;
 
public:
 void fun3();
 virtual int funOver(){return 2;}

virtual int fun4(){return 3;}


};


int main()
{ 
 CMem a,*pMem;
 CMemSub b;
  pMem = &a;
 printf("%d/n",pMem->funOver());
 
  pMem = &b;
  printf("%d/n",pMem->funOver());

 
	
	return 0;
}

The running results of the program are:

[

1

2

]

This is how virtual functions work. Since the object's memory space contains entries to the virtual function table,

The compiler can find the appropriate virtual function from this entry, and the address of this function is no longer determined by the data type.

statements pMem = &b; Make pMem point to the memory space of the object b, call pMem->funOver() When,

The compiler gets the vtable entry for the object b and finds it by this entry CMemSub::funOver() Virtual function address. At this point, the secret of virtual functions has finally come to light. Virtual functions are the focus and difficulty of C++ syntax.

The above is a brief description of C++ virtual functions of the memory allocation mechanism in detail, more information about c++ virtual functions please follow other related articles on this site!


Related articles: