-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpolymorphismVirtual.cpp
More file actions
54 lines (45 loc) · 1.48 KB
/
polymorphismVirtual.cpp
File metadata and controls
54 lines (45 loc) · 1.48 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
48
49
50
51
52
53
54
#include <iostream>
using std::cout; using std::endl;
class Parent {
public:
void Common() const {
cout << "I am part of this family" << endl;
}
//virtual keyword is used to override this method in the derived class
virtual void Identity() const {
cout << "I am the parent" << endl;
}
};
class Child: public Parent {
public:
void Identity() const {
cout << "I am the child" << endl;
}
};
//inherits from Child class, which inherits from Parent class
class GrandChild: public Child {
public:
void Identity() const {
cout << "I am the grandchild" << endl;
}
void Relate() const {
cout << "Grandchild has parent and grandparent" << endl;
}
};
int main() {
//Object/instance of each derived class
Child son;
GrandChild grandson;
//Base class pointer pointing to a derived class object
Parent* ptrChild = &son;
Parent* ptrGrandChild = &grandson;
//-> class pointer operator to call a method of the base class
ptrChild -> Common(); //Inherited method
ptrChild -> Identity(); //Overriding method
ptrGrandChild -> Common(); //Inherited method
ptrGrandChild -> Identity(); //Overriding method
ptrChild -> Parent::Common(); //Explicit method using scope resolution operator
ptrChild -> Parent::Identity(); //Explicit method using scope resolution operator
grandson.Relate(); //via instance
return 0;
}