There is such a problem:
We know that a class with virtual functions in C ++ has a corresponding virtual function table. Is there a virtual table in a pure virtual class? How can I call a pure virtual function if so?
Intuitively, there should be. However, since it is a pure virtual class, it means that its object will never be created, it does not seem necessary to maintain a virtual table.
Can be designedProgramTo verify:
Class Virtualbase
{
Public :
Virtualbase ()
{
// Call pure virtual function through a non virtual function in base class's constructor
Non_virtual_fun ();
}
Void Non_virtual_fun ()
{
Virtual_fun ();
}
Virtual Void Virtual_fun () = 0 ;
};
Class Derived: Public Virtualbase
{
Public :
Virtual Void Virtual_fun (){}
};
Int Main ( Int Argc, Const Char * Argv [])
{
Size_t size = Sizeof (Virtualbase );
Derived D;
}
- Sizeof (virtualbase) returns 4 instead of 1 representing the empty class. This indicates that there is a virtual table pointer inside it, and there is a virtual table pointer, so there is very likely a virtual table.
- Through the above program, we can call the virtualbase constructor when instantiating derived. At this time, we can view the this pointer in the watch window. There is indeed a virtual table pointer pointing to a virtual table.
- A pure virtual function is called through a non-virtual function in the constructor. Although this pure virtual function is implemented in derived, it is still in the base class constructor. Therefore, pure virtual function called-Error
Virtual classes require virtual tables. One reason I can think of is that when override in multiple Derived classes, we need to ensure that the transformed function is at the correct offset address, to ensure that the address is correct, it is important to prepare a template in advance.