-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractShapeExample.cpp
More file actions
48 lines (38 loc) · 1.25 KB
/
AbstractShapeExample.cpp
File metadata and controls
48 lines (38 loc) · 1.25 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
/*Write a program to implement the concept of abstract class in C++.*/
#include <iostream>
using namespace std; // Using namespace to avoid explicit qualification
// Abstract class
class Shape {
public:
// Pure virtual function, making Shape an abstract class
virtual void draw() = 0;
// Virtual destructor is necessary for proper cleanup of derived classes
virtual ~Shape() {}
};
// Derived class: Rectangle
class Rectangle : public Shape {
public:
void draw() override {
cout << "Drawing a rectangle." << endl;
}
};
// Derived class: Circle
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle." << endl;
}
};
int main() {
// You cannot create an instance of an abstract class directly
// Shape shape; // This will give an error
// However, you can use pointers or references to abstract class types
Shape* shape1 = new Rectangle();
Shape* shape2 = new Circle();
shape1->draw(); // Calls the draw() function of the Rectangle class
shape2->draw(); // Calls the draw() function of the Circle class
// Don't forget to delete dynamically allocated objects
delete shape1;
delete shape2;
return 0;
}