Pure virtual class and virtual function table

Source: Internet
Author: User

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.

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.