27派生类的继承过程

派生类的继承过程

派生类如何初始化从基类继承来的成员变量?

  • 派生类继承所有可继承的成员变量和方法,除了构造和析构函数
  • 通过调用基类的构造函数初始化继承来的成员变量,调用基类的析构函数释放继承来的成员变量
  • 通过调用派生类的构造函数初始化新的成员变量,调用派生类的析构函数释放新的成员变量
#include<iostream>
using namespace std;

class base
{
private:
	int ma;
public:
	base(int a):ma(a)
	{
		cout << "base" << endl;
	}
	~base()
	{
		cout << "~base" << endl;
	}

};

class derive:public base
{
private:
	int mb;
public:
	derive(int a, int b) :base(a), mb(b)
	{
		cout << "derive" << endl;
	}
	~derive()
	{
		cout << "~derive" << endl;
	}
};

int main()
{
	int a = 10, b = 20;
	//此处派生类和基类的构造和析构过程是:
	//先派生类调用基类的构造函数,初始化从基类继承来的成员
	//然后调用派生类自己的构造函数,初始化派生类特有的成员
	//当派生类需要释放,则先释放派生类特有成员占用的外部资源,再调用基类的析构函数,释放继承成员占用的外部资源
	derive dd(a, b);
}

一个题目

class Base
{
public:
	Base()
	{
		/*
		push ebp
		mov ebp, esp
		sub esp, 4Ch
		rep stos esp<->ebp 0xCCCCCCCCC
		vfptr <- &Base::vftable
		*/
		cout << "call Base()" << endl;
		clear();
	}
	void clear() { memset(this, 0, sizeof(*this)); }
	virtual void show()
	{
		cout << "call Base::show()" << endl;
	}
};

class Derive : public Base
{
public:
	Derive()
	{
		/*
		push ebp
		mov ebp, esp
		sub esp, 4Ch
		rep stos esp<->ebp 0xCCCCCCCCC
		vfptr <- &Derive::vftable
		*/
		cout << "call Derive()" << endl;
	}
	void show()
	{
		cout << "call Derive::show()" << endl;
	}
};

int main()
{
	Base* pb1 = new Base();
	/*
	mov eax, dword ptr[pb1]
	mov ecx, dword ptr[eax] eax:0x00000000 不是Base::vftable
	call ecx
	*/
	pb1->show();
	delete pb1;

	// 正常运行
	/*Base* pb2 = new Derive();
	pb2->show();
	delete pb2;*/

	return 0;
}
posted @ 2024-01-25 16:44  SIo_2  阅读(13)  评论(0)    收藏  举报