C++对象的内存布局_单一继承

假设如下单一继承关系:


C++代码如下:

class Parent {
public:
	int iparent;
	Parent():iparent(10) {}
	virtual void f() { cout << "Parent::f()" << endl; }
	virtual void g() { cout << "Parent::g()" << endl; }
	virtual void h() { cout << "Parent::h()" << endl; }
};

class Child: public Parent {
public:
	int ichild;
	Child(): ichild(100) {}
	virtual void f() { cout << "Child::f()" << endl; }
	virtual void g_child() { cout << "Child::g_child()" << endl; }
	virtual void h_child() { cout << "Child::h_child()" << endl; }
};

class GrandChild: public Child {
public:
	int igrandchild;
	GrandChild(): igrandchild(1000) {}
	virtual void f() { cout << "GrandChild::f()" << endl; }
	virtual void g_child() { cout << "GrandChild::g_child()" << endl; }
	virtual void h_grandchild() { cout << "GrandChild::h_grandchild()" << endl;}
};

测试代码如下:

int _tmain(int argc, _TCHAR* argv[])
{
	typedef void(*Fun)(void); //函数类型
	GrandChild gc;
	int** pVtab = (int**)&gc;
	cout << "[0] GrandChild::_ptr->" << endl;
	
	for (int i=0; (Fun)pVtab[0][i] !=NULL; i++) {
		Fun pFun = (Fun)pVtab[0][i];
		cout << "   ["<<i<<"] ";
		pFun();
	}

	cout << "[1] Parent.iparent = " << (int)pVtab[1] << endl;
	cout << "[2] Child.ichild = " << (int)pVtab[2] << endl;
	cout << "[3] GrandChild.igrandchild = " << (int)pVtab[3] << endl;

	return 0;
}




从结果我们可以发现,类都会将它的所以虚函数指针放到虚函数列表中。_vfptr是虚指针,指向虚函数地址数组

参考:

http://blog.163.com/xychenbaihu@yeah/blog/static/132229655201210121619750/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值