Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Aside from having a pure virtual function, is there a way to prevent an instantiation of an abstract base class?

I can do this:

class BaseFoo
{
    virtual void blah() = 0;
};

class Foo : public BaseFoo
{
    virtual void blah() {}
};

but I'd like to avoid a vtable. (as per my other question about virtual destructors)

Microsoft ATL has ATL_NO_VTABLE to accomplish this (or at least I think that's what it does...)

like image 281
Jason S Avatar asked Jun 07 '11 22:06

Jason S


People also ask

Can abstract functions prevent instantiation of that class?

Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .

How can we prevent a class from instantiation in CPP?

Solution 1 You can use the Singleton Pattern & its implementation with C++[^].

Does virtual function prevent instantiation of a class?

Declaring a method as pure virtual means that classes that inherit your class will have to implement that method or leave it pure virtual, in which case the derived class will also be an abstract class that cannot be instantiated.


2 Answers

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.

like image 115
Blindy Avatar answered Oct 05 '22 05:10

Blindy


You could make a protected constructor

like image 34
thumbmunkeys Avatar answered Oct 05 '22 06:10

thumbmunkeys