File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments