- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtualFunction.cpp
More file actions
Latest commit
47 lines (38 loc) · 1.16 KB
/
Copy pathvirtualFunction.cpp
File metadata and controls
47 lines (38 loc) · 1.16 KB
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
39
40
41
42
43
44
45
46
47
/*
* Virtual Function
* 1. We cannot use override(C++ 11) keyword if we don't use virtual keyword.
* 2. They are mainly used to achieve Runtime polymorphism.
* 3. It cannot be static.
* 4. A class may have virtual destructor but it cannot have a virtual constructor.
* 5. Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.
* 6. Early Binding (compile time) & late Binding (runtime)
*/
#include<iostream>
classEntity {
public:
Entity() { }
virtual std::string GetName() {
return"Entity";
}
};
classStudent : publicEntity {
private:
std::string name;
public:
Student(const std::string& name) {
this->name = name;
}
std::string GetName() override {
return name;
}
};
voidPrintName(Entity* entity) { // For student pointer, entity type pointer is pointing to student pointer. By default, it will give the priority to the pointer type
std::cout << entity->GetName() << std::endl;
}
intmain()
{
Entity* entity = newEntity(); // Entity type pointer
Student *student = newStudent("Joy Saha"); // student type pointer
PrintName(entity);
PrintName(student);
}