File tree Expand file tree Collapse file tree 2 files changed +66
-1
lines changed Expand file tree Collapse file tree 2 files changed +66
-1
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -12,7 +12,7 @@ using namespace std;
12
12
class Person {
13
13
public:
14
14
// does runtime binding of intro() based on the type of object is used to invoke the method
15
- virtual void intro () {
15
+ void intro () {
16
16
cout<<" Hello I am a Person" <<endl;
17
17
}
18
18
};
@@ -42,6 +42,7 @@ int main() {
42
42
Person p;
43
43
Anish a;
44
44
Mrinal m;
45
+ a.intro ();
45
46
getIntro (a);// without virtual base function , it would have printed the base method value
46
47
getIntro (m);
47
48
You can’t perform that action at this time.
0 commit comments