Skip to content

Commit 728d314

Browse files
committed
Add Virtual Functions in C++
1 parent 3613865 commit 728d314

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

HelloWorld/src/Main.cpp

+14-17
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,31 @@
33
class Entity
44
{
55
public:
6-
float X, Y;
7-
8-
void Move(float xa, float ya)
9-
{
10-
X += xa;
11-
Y += ya;
12-
}
6+
virtual std::string GetName() { return "Entity"; }
137
};
148

159
class Player : public Entity
1610
{
11+
private:
12+
std::string m_Name;
1713
public:
18-
const char* Name;
14+
Player(const std::string& name) : m_Name(name) {}
1915

20-
void PrintName()
21-
{
22-
std::cout << Name << std::endl;
23-
}
16+
std::string GetName() override { return m_Name; }
2417
};
2518

19+
void PrintName(Entity* entity)
20+
{
21+
std::cout << entity->GetName() << std::endl;
22+
}
23+
2624
int main()
2725
{
28-
std::cout << sizeof(Entity) << std::endl;
29-
std::cout << sizeof(Player) << std::endl;
26+
Entity* e = new Entity();
27+
PrintName(e);
3028

31-
Player player;
32-
player.Move(5, 5);
33-
player.X = 2;
29+
Player* p = new Player("Cherno");
30+
PrintName(p);
3431

3532
std::cin.get();
3633
}

0 commit comments

Comments
 (0)