-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cpp
More file actions
59 lines (49 loc) · 1.08 KB
/
main.cpp
File metadata and controls
59 lines (49 loc) · 1.08 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
/**
This example shows the interface using virtual functions in C++.
*/
#include <iostream>
#include <memory>
class Shape
{
public:
virtual double
area() const = 0; // Pure virtual function
virtual ~Shape() {} // Virtual destructor
};
class Circle : public Shape
{
private:
double radius;
public:
Circle(double r) : radius(r) {}
double
area() const override
{
return 3.14159 * radius * radius;
}
};
class Rectangle : public Shape
{
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double
area() const override
{
return width * height;
}
};
int
main()
{
std::unique_ptr<Shape> shapes[2];
shapes[0] = std::make_unique<Circle>(5.0);
shapes[1] = std::make_unique<Rectangle>(4.0, 6.0);
// The following line would cause a compilation error because Shape is an abstract class
// Shape a = new Shape();
for (int i = 0; i < 2; ++i) {
std::cout << "Area of shape " << i + 1 << ": " << shapes[i]->area() << std::endl;
}
return 0;
}