Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ abstract class without pure virtual functions?

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.

like image 711
MintyAnt Avatar asked Jan 31 '13 17:01

MintyAnt


People also ask

Can abstract class have non virtual function?

Abstract classes (apart from pure virtual functions) can have member variables, non-virtual functions, regular virtual functions, static functions, etc.

Which class has no pure virtual function?

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.

How abstract class is related to 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.

Do virtual functions make a class abstract?

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).


2 Answers

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.

like image 88
NPE Avatar answered Sep 19 '22 15:09

NPE


Try using a protected constructor

like image 33
Aditya Sihag Avatar answered Sep 21 '22 15:09

Aditya Sihag