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.
Abstract classes (apart from pure virtual functions) can have member variables, non-virtual functions, regular virtual functions, static functions, etc.
Explanation: Pure virtual function has no implementation in the base class whereas virtual function may have an implementation in the base class. The base class has at least one pure virtual function.
A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in the declaration. An abstract class is a class in C++ which have at least one pure virtual function.
Any class that has at least one pure virtual function is known as an abstract class. An abstract class cannot be instantiated (i.e. you cannot build an object of this class type).
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.
Try using a protected constructor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With