Explanation of pure virtual functions in C ++

Source: Internet
Author: User

If the base class defines a virtual function, and the inheritance class does not reload this virtual function, in the virtual function table of the base class and the inheritance class, their virtual function addresses are the same. If you reload this virtual function, the addresses of the virtual functions in the two virtual functions are different. Therefore, we made a validation of this statement on the visual c 6.0 platform. See:
1. When the inherited class does not overload the virtual function defined by the base class
# Include <iostream. h>
Class
{
Public:
Virtual void f ()
{
Cout <"class A" <endl;
};
};

Class B: public {};

Int main ()
{
A * pa = new;
Int * paadd = (int *) (* (int *) pa );
Int * paaddr = (int *) (* (int *) paadd );
Cout <paaddr <endl;
A * pb = new B;
Int * pbadd = (int *) (* (int *) pb );
Int * pbaddr = (int *) (* (int *) pbadd );
Cout <pbaddr <endl;
Delete pa;
Delete pb;
Return 0
}

The output is indeed the same, all of which are 0x00401028 (note: the addresses on different machines may be different)

2. When the inheritance class reloads the virtual functions defined by the base class
# Include <iostream. h>
Class
{
Public:
Virtual void f ()
{
Cout <"class A" <endl;
};
};
Class B: public
{
Public:
Virtual void f ()
{
Cout <"class B" <endl;
};
};
Int main ()
{
A * pa = new;
Cout <sizeof (* pa) <endl;
Int * paadd = (int *) (* (int *) pa );
Int * paaddr = (int *) (* (int *) paadd );
Cout <paaddr <endl;
A * pb = new B;
Int * pbadd = (int *) (* (int *) pb );
Int * pbaddr = (int *) (* (int *) pbadd );
Cout <pbaddr <endl;
Delete pa;
Delete pb;
Return 0;
}
In this case, the virtual function address of the base class is: 0x00401028, and the virtual function address of the inherited class is: 0x00401032.

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.