* pmatos:
I'm having a design problem. Imagine a Shape class that can be a
Square, a Rectangle or a Triangle. Shape should be an abstract class.
Now, I want to create a stack of Shapes.
I do
stack<Shape> shapeStack;
For some reason (probably because Shape is abstract) this is not
working, it results in a compile time error. How can I solve this
issue?
Create a stack of non-abstract things. The most fundamental way is
stack<Shape*> shapeStack;
where each element of the stack is a pointer to a non-abstract object.
To automate destruction of those objects you can use boost::shared_ptr,
typedef boost::shared_ptr<Shape> ShapePtr;
stack<ShapePtr> shapeStack;
See <url: http://www.boost.org/>.
(Now, another question, if a class has at least a virtual member, does
it need to have a virtual destructor? If yes, why?)
No, it does not necessarily need a virtual destructor. However, there's
essentially no added cost for the virtual destructor then, and it allows
objects to be destroyed without knowing the exact type. Which you need
for e.g. your shapeStack.
If you define a destructor you probably also need to define a copy
constructor and an assignment operator, or make those private and
unimplemented.
This is commonly called the "rule of three": given that you need one of
them, you probably need (to take charge of) all of them.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?