#include <iostream>
#include <memory>
#include <vector>
class Shape {
public:
virtual void draw() const {
std::cout << "Draw a generic shape" << std::endl;
}
virtual ~Shape() {
std::cout << "Shape destructor" << std::endl;
}
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Draw a circle ⚪" << std::endl;
}
~Circle() override {
std::cout << "Circle destructor" << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() const override {
std::cout << "Draw a rectangle ◻️" << std::endl;
}
~Rectangle() override {
std::cout << "Rectangle destructor" << std::endl;
}
};
class Triangle : public Shape {
public:
void draw() const override {
std::cout << "Draw a triangle ▲" << std::endl;
}
~Triangle() override {
std::cout << "Triangle destructor" << std::endl;
}
};
int main() {
std::cout << "=== C++ Polymorphism Demo Program ===" << std::endl;
std::cout << "\n--- Raw pointer method ---" << std::endl;
Shape* shapes[] = {
new Circle(),
new Rectangle(),
new Triangle()
};
for (int i = 0; i < 3; ++i) {
shapes[i]->draw();
}
for (int i = 0; i < 3; ++i) {
delete shapes[i];
}
std::cout << "\n--- Smart pointer method (recommended) ---" << std::endl;
std::vector<std::unique_ptr<Shape>> shapeList;
shapeList.push_back(std::make_unique<Circle>());
shapeList.push_back(std::make_unique<Rectangle>());
shapeList.push_back(std::make_unique<Triangle>());
for (const auto& ptr : shapeList) {
ptr->draw();
}
std::cout << "\n--- Reference method ---" << std::endl;
Circle c;
Rectangle r;
Triangle t;
auto callDraw = [](const Shape& shape) {
shape.draw();
};
callDraw(c);
callDraw(r);
callDraw(t);
std::cout << "\nProgram ending, all objects will be automatically destructed (smart pointers and stack objects)" << std::endl;
return 0;
}