-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtualFunc.cpp
More file actions
126 lines (106 loc) · 2.07 KB
/
Copy pathvirtualFunc.cpp
File metadata and controls
126 lines (106 loc) · 2.07 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//Example of virtual function
//Prithwiraj Shome
#include <iostream>
using namespace std;
typedef enum area_type {
CIRCLE_AREA,
RECTANGLE_AREA,
UNKNOWN
}AREA_TYPE;
//Base class
typedef class Shape {
protected:
AREA_TYPE type = UNKNOWN;
double height = 0;
double width = 0;
double radius = 0;
const double pi = 3.14;
public:
Shape() {};
Shape(double h, double w, double r)
{
height = h;
width = w;
radius = r;
}
void setType(AREA_TYPE t)
{
type = t;
}
virtual void show() // Virtual function but not Pure
{
if (type == RECTANGLE_AREA) {
cout << "Height = " << height << endl;
cout << "Width = " << width << endl;
}
else if (type == CIRCLE_AREA) {
cout << "Radius = " << radius << endl;
}
}
// Virtual Function
virtual double area(void) // Virtual function but not Pure
{
if (type == RECTANGLE_AREA)
{
cout << "Base Class Rectangle Area : ";
return (height * width);
}
else if (type == CIRCLE_AREA)
{
cout << "Base Class Circle Area : ";
return (pi * radius * radius);
}
else {
cout << "Base Class Area Error: ";
return 0;
}
}
}SHAPE;
typedef class Rectangle : public SHAPE {
public:
Rectangle(double h, double w)
{
height = h;
width = w;
}
double area(void)
{
return (height * width);
}
void show()
{
cout << "Rectangle Height = " << height << endl;
cout << "Rectangle Width = " << width << endl;
}
}RECTANGLE;
typedef class Circle : public SHAPE {
public:
Circle(double r)
{
radius = r;
}
double area(void)
{
return (pi * radius * radius);
}
void show()
{
cout << "Circle Radius = " << radius << endl;
}
}CIRCLE;
int main(void)
{
SHAPE* rPtr = new RECTANGLE(3, 4);
rPtr->show();
cout << "Rectangle area is = " << rPtr->area() << " unit square" << endl;
SHAPE * cPtr = new CIRCLE(1);
cPtr->show();
cout << "Circle Area is = " << cPtr->area() << " unit square" << endl;
SHAPE* basePtr = new SHAPE(2,3,4);
basePtr->setType(CIRCLE_AREA);
basePtr->show();
cout << basePtr->area() << endl;
basePtr->setType(RECTANGLE_AREA);
basePtr->show();
cout << basePtr->area() << endl;
}