开发者

Making a class abstract without any pure virtual methods

开发者 https://www.devze.com 2023-02-03 13:16 出处:网络
I have a class which is to listen to mouse events. However, I do not want to force the user to implement a开发者_如何学Pythonny specific one, but I do want to make it clear that they must inherit it.

I have a class which is to listen to mouse events. However, I do not want to force the user to implement a开发者_如何学Pythonny specific one, but I do want to make it clear that they must inherit it.

Is there a way to do this?

Thanks


You can declare a pure virtual destructor, but give it a definition. The class will be abstract, but any inheriting classes will not by default be abstract.

struct Abstract
{
     virtual ~Abstract() = 0;
};

Abstract::~Abstract() {}

struct Valid: public Abstract
{
        // Notice you don't need to actually overide the base
        // classes pure virtual method as it has a default
};


int main()
{
    // Abstract        a;  // This line fails to compile as Abstract is abstract
    Valid           v;  // This compiles fine.
}


Specify the constructor of the base as protected. This does mean that you cannot construct it directly, but forces inheritance. There is nothing that makes a developer inherit from that class aside from good documentation though!

Example:

struct Abstract {
protected:
    Abstract() {}
};

struct Valid: public Abstract {
    // No need to override anything.
};


int main() {
    // Abstract a;  // This line fails constructor is protected
    Valid v;  // This compiles fine.
}


You can declare your base class as having a pure virtual destructor that you implement. Since a destructor is always provided by the compiler, the derived class won't be purely virtual, but the base class can't directly be instantiated. You should always declare a destructor as virtual anyway, so this will have no overhead.

class Base
{
public:
    virtual ~Base() = 0;
    virtual void SomeVirtualMethod();
};

inline Base::~Base()
{
}

class Derived : public Base
{
};

inline Base* createBase()
{
    // return new Base; // <- This won't compile
    return new Derived; // <- This does compile, Derived is not a pure virtual class !
}


Why would you want the user to inherit, if he does not have to implement anything.

When the base class is needed to be able to put all the "eventhandlers" in a std::set. Then no one can create a class and put it in this set without subclassing your base class. Because the set will be defined as

std::set<MyBaseClass*> mySet;


By definition, an abstract class is a class which has at least one pure virtual function. For your purpose, you can define the destructor to be pure virtual, and provide an implementation:

class abstract { 
        virtual ~abstract()=0; 
}; 

abstract::~abstract() {} 

By default, all inheriting classes will not be abstract, even though they will not need to implement any method.

0

精彩评论

暂无评论...
验证码 换一张
取 消