Skip to content

Commit 3cb13cc

Browse files
committed
Inherited Virtual function and hierarchy nature of classes
1 parent 263f3da commit 3cb13cc

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

VirtualFuncInheritence.cpp

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include<iostream>
2+
3+
using namespace std;
4+
5+
//inheritence of virtual method attributes, and virtual functions and hierarchy of class
6+
7+
class Person {
8+
public:
9+
virtual void intro() {
10+
cout<<"Hi I am a person"<<endl;
11+
}
12+
};
13+
14+
class Anish : public Person { //inherits from class Person
15+
public:
16+
void intro() { //function overridden
17+
18+
cout<<"Hi I am Anish derived from class Person"<<endl;
19+
20+
}
21+
22+
};
23+
24+
25+
class Mrinal : public Anish { //inherits from class Anish
26+
public :
27+
void intro() {
28+
cout<<"Hi I am Mrinal derived from class Anish"<<endl;
29+
}
30+
31+
};
32+
33+
34+
//making a function which takes the argument as Object of Class Person or refers/pointer to a type Person
35+
void getIntro(Person *p)
36+
{
37+
p->intro(); //function of derived class will be executed
38+
39+
}
40+
41+
42+
int main() {
43+
44+
Person *p1,*p2;
45+
Anish a;
46+
Mrinal m;
47+
p1=&a; // pointer p1 of type Person refers the derived(Anish class) object
48+
p2=&m; //pointer p2 of type Person refers to the derived class of Anish ie Mrinal
49+
50+
p1->intro();
51+
p2->intro();
52+
53+
// getIntro(p); //person class method called
54+
getIntro(&a); // Anish class overridden function called
55+
getIntro(&m); // Mrinal class overridden function called
56+
57+
//without declaring a virtual base class function,the 3 above all function calls would return "Hi I am a person" i.e method of base class due
58+
//to static binding-binding during compiletime
59+
60+
61+
62+
63+
return 0;
64+
}

VirtualFunctions.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ using namespace std;
1212
class Person {
1313
public:
1414
//does runtime binding of intro() based on the type of object is used to invoke the method
15-
virtual void intro() {
15+
void intro() {
1616
cout<<"Hello I am a Person"<<endl;
1717
}
1818
};
@@ -42,6 +42,7 @@ int main() {
4242
Person p;
4343
Anish a;
4444
Mrinal m;
45+
a.intro();
4546
getIntro(a);//without virtual base function , it would have printed the base method value
4647
getIntro(m);
4748

0 commit comments

Comments
 (0)