Skip to content

Commit 263f3da

Browse files
committed
Virtual function and runtime polymorphism
1 parent c51082e commit 263f3da

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

VirtualFunctions.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include<iostream>
2+
//RUNTIME POLYMORPHISM - Virtual functions are used to achieve runtime polymorphism. It is achieved by function overriding(re-defination)
3+
// of base class method which is re-defined in a derived class.
4+
5+
//Then a pointer of type base class is created which refers to derived class object
6+
//and the base method is called , which actually executes the derived class version
7+
//method.
8+
//Dynamic binding is done i.e during runtime
9+
10+
using namespace std;
11+
12+
class Person {
13+
public:
14+
//does runtime binding of intro() based on the type of object is used to invoke the method
15+
virtual void intro() {
16+
cout<<"Hello I am a Person"<<endl;
17+
}
18+
};
19+
20+
class Anish : public Person {
21+
public:
22+
void intro() { //function overridden
23+
cout<<"This is Anish"<<endl;
24+
}
25+
};
26+
27+
class Mrinal : public Person {
28+
public:
29+
void intro() {
30+
cout<<"Hi this is Mrinal"<<endl;
31+
}
32+
};
33+
34+
35+
void getIntro(Person &p) {
36+
p.intro();
37+
}
38+
39+
40+
int main() {
41+
42+
Person p;
43+
Anish a;
44+
Mrinal m;
45+
getIntro(a);//without virtual base function , it would have printed the base method value
46+
getIntro(m);
47+
48+
return 0;
49+
}

0 commit comments

Comments
 (0)