Calling virtual functions in C + + constructors

Source: Internet
Author: User

Talking about the case of calling virtual functions in constructors, only single inheritance is discussed, regardless of virtual inheritance and multiple inheritance. Test platform: VS2013 + win7x64
An example: #include <stdlib.h>
#include <stdio.h>

Class Base
{
Private
int __data;

Public
Base ()
{
This->func ();
}

Public
virtual void Func ()
{
printf ("Base::func");
}
};

Class Deri:public Base
{
Public
Deri ()
{This->func ();
}


Public
virtual void Func ()
{
printf ("deri::func\n");
}

};

int main (int argc, char** argv)
{
Deri D;

GetChar ();
return 0;
}
Output: Base::funcderi::func
First, we discuss the construction of Object D. 1 first constructs the base class part, calls the base class base the constructor, at this time, the derived class part has not produced, when the virtual table should be the binding base class, naturally calls the Base::func ()
2 again constructs the derived class part, at this time, the virtual table changes, binds on the derived class, calls Deri::func ()
Although there is an overloaded Func function in a derived class, the member data of the derived class is not initialized when you construct the base class part, and if you call Func in a derived class, it can cause errors, memory out of bounds, or even crashes.

In the function, you can print the virtual table address:
--Base::func () int* VTL = (int*) * ((int*) this), Std::cout << "Base:" << this << "VTable:" << vtl << Std::endl;
--Deri::func () int* VTL = (int*) * ((int*) this), Std::cout << "Deri:" << this << "VTable:" << vtl << Std::endl;
Output: base:0028f980 vtable:003fdc78
deri:0028f980 vtable:003fdc98
found that the address of the virtual table is constantly changing.


Calling virtual functions in C + + constructors

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.