虚函数,虚表,虚指针

虚函数:虚函数是一种函数,其行为可被子类中的函数覆盖。虚函数与非虚函数的区别在于,非虚函数的地址在编译期确定(也称之为早期绑定、静态绑定),虚函数的地址在运行期确定(也称之为晚期绑定、动态绑定)。

虚表:如果一个类有虚函数,那么编译器会为该类生成的一个虚表,其中存放指向该类虚函数地址的函数指针。

虚指针:在运行期,当创建某个含有虚函数类的对象时,会为该对象添加一个隐藏的成员变量——虚指针,该指针指向该类的虚表。

 

 Virtual Method, Virtual Table and Virtual Pointer

Virtual Method: A virtual method is a method whose behavior can be overridden within an inheriting class by a function with the same signature. The difference between a non-virtual member method and a virtual member method is, the non-virtual member methods are resolved at compile time. This mechanism is called static binding. Where as the virtual member methods are resolved during run-time. This mechanism is known as dynamic binding.

Pure Virtual Function: E.g., virtual void fun() = 0; This class is a abstract class.

Virtual Table: If a class has virtual methods, the compiler will create a virtual table for the class. The virtual table stores pointers to the virtual functions.

Virtual Pointer: When an object is created, a virtual pointer is added as a hidden member of this object. The virtual pointer points to the virtual table.

 

你可能感兴趣的:(function,table,Class,compiler,methods,Pointers)