// 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.
*/
In Cases of Virtual Keyword in CPP14
于 2022-11-25 20:17:04 首次发布