Created
August 24, 2012 02:11
-
-
Save shihongzhi/3444738 to your computer and use it in GitHub Desktop.
在构造函数中调用虚函数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdafx.h" | |
using namespace std; | |
class C180 | |
{ | |
public: | |
C180() { | |
foo(); | |
this->foo(); | |
} | |
virtual void foo() { | |
//*this == *(void**)this | |
cout << "<< C180.foo this: " << this << " vtadr: " << *(void**)this << endl; | |
} | |
}; | |
class C190 : public C180 | |
{ | |
public: | |
C190() {} | |
virtual void foo() { | |
cout << "<< C190.foo this: " << this << " vtadr: " << *(void**)this << endl; | |
} | |
}; | |
int _tmain(int argc, _TCHAR* argv[]) | |
{ | |
C190 obj; | |
//output: | |
//<< C180.foo this: " << this << " vtadr: " << *(void**)this | |
//<< C180.foo this: " << this << " vtadr: " << *(void**)this | |
obj.foo(); | |
//output: | |
//"<< C190.foo this: " << this << " vtadr: " << *(void**)this | |
getchar(); | |
return 0; | |
} | |
//标准中提到:这是一种特例,在这种情况下,即在构造子类时调用父类的构造函数,而父类的构造函数中又调用了虚成员函数,这个虚成员函数即使被子类重写,也不允许发生多态的行为。 | |
//因为这种情况下的实例化子类对象是,会先调用父类的构造函数, | |
//然后父类构造函数申请相应对象的内存空间,得到指向这段内存空间的this指针,同时构建vtable,用vtable point指向刚刚建立的vtable,vtable中写了虚函数C180:foo的指针。 | |
//然后在调用子类的构造函数,因为重载了foo虚函数,所以用指向C190:foo的指针覆盖vtable中虚函数C180:foo的指针, 这样就实现了多态。 | |
//而在父类构造函数中调用虚函数foo时,那是vtable中还是保存着虚函数C180:foo的指针,所以调用的是C180:foo函数。 |
Author
shihongzhi
commented
Aug 25, 2012
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment