C++ virtual keyword

C++ virtual keyword

In C++, functions modified by the virtual keyword are called virtual functions.

We know that there are three major characteristics in C++ syntax, encapsulation, inheritance, and polymorphism .

Here we focus on polymorphism. Polymorphism is simply understood as the same interface but different forms . Specifically, the interface is the same, the function name is the same, the incoming parameters are different, the function called is different, and the resulting form is different.

Polymorphism is generally divided into three categories:
1. Static polymorphism, which determines the function call at the compilation stage
2. Dynamic polymorphism, which determines the function call at the runtime
3. Macro polymorphism, determines the function call
and virtual modified functions at the pre-compilation stage That is, virtual functions provide support for dynamic polymorphism here.

Virtual function processing flow:
first generate symbols in the compilation stage, and then put the generated virtual function symbols not only in the symbol table, but also in the read-only data section (.rodata), and in the read-only data section The stored things exist in the form of a structure, which is the virtual function table (vftable) . The virtual function table is generated during the compilation stage. After the virtual function table is generated, it is assembled and linked. The link stage will merge all segments, including .rodata , the entry address of the virtual function is stored in the virtual function table; then when the instructions and data are loaded in the runtime phase, the entry address of the virtual function in the virtual function table will be loaded In the memory, in this way, the call of the function can be determined at the running stage, which is the realization of dynamic polymorphism.

#include <iostream>
class Base
{
    
    
public:
 Base(int a) : ma(a) {
    
    }
 virtual void Show()
 {
    
    
  std::cout << "ma : " << ma << std::endl;
 }
protected:
 int ma;
};

class Derive : public Base
{
    
    
public:
 Derive(int b) : mb(b), Base(b){
    
    }
 void Show()
 {
    
    
  std::cout << "mb : " << mb << std::endl;
 }
protected:
 int mb;
};

int main()
{
    
    
 Base* pb = new Derive(10);
 std::cout << sizeof(Base) << std::endl;//8
 std::cout << sizeof(Derive) << std::endl;//12
 std::cout << typeid(pb).name() << std::endl;//class Base *
 std::cout << typeid(*pb).name() << std::endl;//class Derive
 pb->Show();
 return 0;
}

Guess you like

Origin blog.csdn.net/qq_43579888/article/details/104174065