In Cases of Virtual Keyword in CPP14

// In cases of virtual keyword in CPP14
// author: kagula
// last-update-date: 2022-11-25
// environment: Microsoft Visual Studio Community 2019 Version 16.11.13
// Description:
//		"virtual" as "i can be overrided".

#include <iostream>

using namespace std;

class Bird {
public:
	Bird()
	{
		cout << "a Bird initialization\n";
	}

	void doSomething()
	{
		cout << "a Bird do something.\n";
	}

	virtual void doSomethingInVirtual()//Suggest to add virtual whether it will be used.
	{
		//virtual prefix indicated i can be overrided if i is a pointer of Bird but which pointer actually point to Bird.
		cout << "virtual version a Bird do something .\n";
	}

	//virtual void doNothing() = 0;//this sentence like the method of interface in java.

	virtual ~Bird()
	{
		cout << "a Bird destruct.\n";
	}
};

class Eagle :public Bird {
public:
	Eagle()
	{
		cout << "a Eagle initialization\n";
	}

	void doSomething()
	{
		cout << "a Eagle do something.\n";
	}

	void doSomethingInVirtual()
	{
		cout << "a Eagle do something.\n";
	}

	virtual ~Eagle()
	{
		cout << "a Eagle destruct.\n";
	}
};

int main()
{
	std::cout << "Test Virtual Keyword!\n";//endl extra do clear output buffer so slowly than "\n".

	{
		//When using the pointer of bird which actually point to eagle, then virtual function is appear.
		//I can regard virtual keyword as i can be override by children.
		Bird* pBird = new Eagle();

		pBird->doSomething();//output 'a Bird do something.'
		pBird->doSomethingInVirtual();//output 'a Eagle do something.'

		delete pBird; //will not call the destructor of Eagle if no virtual prefix at the destructor of Bird.
	}

	cout << endl;

	{
		unique_ptr<Bird> pBird = make_unique<Eagle>();

		pBird->doSomething();
		pBird->doSomethingInVirtual();

		//will not call the destructor of Eagle if no virtual prefix at the destructor of Bird.
	}

	cout << endl;

	{
		shared_ptr<Eagle> pEagle = make_unique<Eagle>();
		shared_ptr<Bird> pBird = static_pointer_cast<Bird>(pEagle);//unique_ptr can not be used here.

		pBird->doSomething();
		pBird->doSomethingInVirtual();

		//whether or not virtual prefix at the destructor of Bird, the destructor of Eagle will be called.
	}

	const int n = getchar();
}

/*
* Virtual Inherit
*
* class BaldEagle: pulic virtual Eagle
* class RedEagle: pulic virtual Eagle
*
* class ANut: pulic BaldEagle, public RedEagle
*
* As be told by some material, 'A Nut' will inherit Eagle only once, but i do not want to test it for so rare occasion.
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kagula086

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值