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...)
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 .
Solution 1 You can use the Singleton Pattern & its implementation with C++[^].
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With