-
Notifications
You must be signed in to change notification settings - Fork 0
/
19.pure_virtual_functions.cpp
38 lines (29 loc) · 1.04 KB
/
19.pure_virtual_functions.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
// pure virtual functions allows us to define a function in a base class that does not have an implementations
// and then force subclasses to actually implement that function
class Entity
{
public:
virtual std::string GetName() = 0; // in some cases it doesnt make sense to provide this default implementations
// we might want to force the subclass to provide its own definition for a certain function\
// by = 0 means it has to be implemented in subclass
};
class Player : public Entity
{
private:
std::string m_name;
public:
Player(const std::string& name)
: m_name(name) {}
std::string GetName() override {return m_name;}
};
int main()
{
Entity* e = new Player(""); // you can only instantiate the class only if it has all those pure virtual functions implemented
std::cout << e->GetName() << std::endl;
Player* p = new Player("fati") ;
std::cout << p->GetName() << std::endl;
Entity* entity = p;
std::cout << entity->GetName() << std::endl;
std::cin.get();
}