Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...