C++: any way to prevent any instantiation of an abstract base class?

不羁岁月 提交于 2019-12-03 23:29:53

A really obvious way is to declare a protected constructor, and to declare public constructors in the non-abstract derived classes.

This of course shifts the burden of corectness to the derived classes, but at least the base class is protected.

You could make a protected constructor

If you make a protected constructor as advised here, then when your derived class is constructed you'll get an error akin to, "cannot access private member declared in class", with some other information specific to your classes.

If you have pure virtual methods in your base class, then the problem isn't that those are instantiated (and it's certainly not that non-abstract methods are instantiated), but the problem occurs at destruction time when the compiler can not infer what your derived class owns. That, or you have instantiated stuff without an owner! (ruh roh rhaggy)

Declare a pure virtual destructor for your base class and then implement it externally. Also, never, ever make a constructor private (edit: unless it is guaranteed to only be used internally, such as automatic construction of the next node in a linked list). The closest you'll ever want (edit: otherwise) is an explicit constructor (but that's another topic).

edits: I may have found the answer, but I still can't type today.

// example.h

class A
{

    A ( ) { }
    virtual ~A ( ) = 0;
};

class B : public A
{
    B ( ) { }
    ~B ( ) { }
};

// example.cpp
#include "example.h"

A::~A ( ) { }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!