-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgeneralPolymorphism.cpp
52 lines (43 loc) · 1.03 KB
/
generalPolymorphism.cpp
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
/*
* Program to understand polymorphism
*/
#include <iostream>
using namespace std;
class Shape {
protected:
int width;
int height;
public:
// constructor or in general functions
// can have default arguments
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
virtual void area() {
cout << "Parent class area called!" << endl;
}
};
class Rectangle: public Shape {
public:
Rectangle(int a = 0, int b = 0) : Shape(a, b) {}
// polymorphism
// area function is also defined in the base class
void area() {
cout << "Rectangle class area: " << width*height << endl;
}
};
int main () {
Shape *shape;
Rectangle r(10, 20);
shape = &r;
// this will call the area() function of Shape class
// but we want it to call area() function of Rectangle class
shape->area();
// static binding / early binding
// the call to area() of Shape is fixed at compilation time itself
// to call area() of Rectangle
// define area() function as virtual function in Shape class
// it tells the compiler not to do static linkage
return 0;
}