C++ abstract class without pure virtual functions?

MintyAnt picture MintyAnt · Jan 31, 2013 · Viewed 15.5k times · Source

I have a base class

class ShapeF
{
public:
    ShapeF();
    virtual ~ShapeF();

    inline void SetPosition(const Vector2& inPosition) { mPosition.Set(inPosition); }

protected:
    Vector2 mPosition;
}

Obviously with some ommitied code, but you get the point. I use this as a template, and with some fun (ommited) enums, a way to determine what kind of shape i'm using

class RotatedRectangleF : public ShapeF
{
public:
    RotatedRectangleF();
    virtual ~RotatedRectangleF();
protected:
    float mWidth;
    float mHeight;
    float mRotation;
}

ShapeF does its job with the positioning, and an enum that defines what the type is. It has accessors and mutators, but no methods.

Can I make ShapeF an abstract class, to ensure nobody tries and instantiate an object of type ShapeF?

Normally, this is doable by having a pure virtual function within ShapeF

//ShapeF.h
virtual void Collides(const ShapeF& inShape) = 0;

However, I am currently dealing with collisions in a seperate class. I can move everything over, but i'm wondering if there is a way to make a class abstract.. without the pure virtual functions.

Answer

NPE picture NPE · Jan 31, 2013

You could declare, and implement, a pure virtual destructor:

class ShapeF
{
public:
    virtual ~ShapeF() = 0;
    ...
};

ShapeF::~ShapeF() {}

It's a tiny step from what you already have, and will prevent ShapeF from being instantiated directly. The derived classes won't need to change.