Skip to content
Github code
Explanation
- Base Class
Shape: This is an abstract class with two pure virtual functions: area() and describe(). The destructor is virtual to ensure proper cleanup when deleting derived objects.
- Derived Classes
Circle, Rectangle, and Triangle: These classes inherit from Shape and provide specific implementations for the area() and describe() methods. Each class has its own unique member variables (like radius for Circle and width, height for Rectangle).
- Dynamic Memory Allocation: In the
main() function, we dynamically allocate memory for objects of the derived classes using new and store the pointers in Shape* pointers. This demonstrates how pointers to base class objects can point to derived class objects.
- Polymorphism: The
describe() and area() methods are called on the base class pointers, but the version from the appropriate derived class is executed, demonstrating polymorphism in action.
- Memory Management: Finally, the dynamically allocated objects are deleted to avoid memory leaks.