-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_003.cpp
More file actions
48 lines (39 loc) · 938 Bytes
/
problem_003.cpp
File metadata and controls
48 lines (39 loc) · 938 Bytes
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
//Write a C++ program to illustrate virtual function implementation
#include <iostream>
using namespace std;
class Shape {
public:
virtual void area() {
cout << "Shape's area" << endl;
}
};
class Circle : public Shape {
private:
float radius;
public:
Circle(float r) : radius(r) {}
void area() {
cout << "Circle's area: " << 3.14 * radius * radius << endl;
}
};
class Rectangle : public Shape {
private:
float length;
float width;
public:
Rectangle(float l, float w) : length(l), width(w) {}
void area() {
cout << "Rectangle's area: " << length * width << endl;
}
};
int main() {
Shape* s=new Shape();
Shape* shape1 = new Circle(5);
Shape* shape2 = new Rectangle(12, 4);
s->area();
shape1->area(); // Calls Circle's area() method
shape2->area(); // Calls Rectangle's area() method
delete shape1;
delete shape2;
return 0;
}