对象切割时虚指针VPTR探索

#include 
#include 
#include "ThreadPool.h"
#include 
using namespace std;


class A
{
public:
	virtual void go()
	{
		cout << "A::go()\n";
	}

	virtual void to()
	{
		cout << "A::to()\n";
	}

	void printA()
	{
		printf("A::a = %d\n",a);
	}
private:
	int a{10};
	friend class B;
};

class B:public A
{
public:
	B()
	{
		a = 11;
	}
	virtual void go()
	{
		cout << "B::go()\n";
	}

	virtual void tes()
	{
		cout << "B::tes()\n";
	}

	void printB()
	{
		printf("B::a = %d\n", a);
	}
private:
	int b{ 20 };
};

typedef void (*pFUNC)();
int main()
{
	B b;
	b.printB();

	A a = b;
	a.printA();
	long* pAddresB = (long*)& b;
	long* vptr_b = (long*)(*pAddresB);

	long* pAddresA = (long*)& a;
	long* vptr_a = (long*)(*pAddresA);

	printf("B的VPTR=%p\n", vptr_b);
	printf("A的VPTR=%p\n", vptr_a);

	pFUNC f1 = (pFUNC)vptr_b[0];
	f1();


	system("pause");
	return 0;
}

结果:
对象切割时虚指针VPTR探索_第1张图片
从结果可以看出对象切割并没覆盖其基类的vptr指针值

你可能感兴趣的:(深度探索c++对象模型,c++)