I am new to C++ and would like to know if the use of a virtual destructor is required in the following program:
#include <iostream>
class Shape2D {
protected:
int firstDimension;
int secondDimension;
public:
Shape2D(int a, int b) {
firstDimension = a;
secondDimension = b;
}
virtual void getArea() {
std::cout << "Area undefined." << std::endl;
}
};
class Rectangle : public Shape2D {
public:
Rectangle(int length=0, int width=0) : Shape2D(length, width) {
}
void getArea() {
int area = firstDimension*secondDimension;
std::cout << "Area of rectangle: " << area << " sq units." << std::endl;
}
};
int main()
{
Rectangle rct(4, 5); // stack allocated derived object
Shape2D *sh = &rct; // base pointer to derived object
sh->getArea();
// object goes out of scope here.
}
I was reading this post and the most upvoted answer said that the use of a virtual destructor is suitable whenever we want to delete a derived object allocated by new
through its base pointer. However, in this context, we are allocating a derived object Rectangle
on the stack in the main
routine and the base pointer is not being delete
-ed so would it matter if a virtual destructor is provided?