Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a class abstract without any pure virtual methods

Tags:

c++

I have a class which is to listen to mouse events. However, I do not want to force the user to implement any specific one, but I do want to make it clear that they must inherit it.

Is there a way to do this?

Thanks

like image 736
jmasterx Avatar asked Jan 09 '11 18:01

jmasterx


People also ask

How can we create abstract class without abstract method?

And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it. Hence, if you want to prevent instantiation of a class directly you can declare it abstract.

Do all of the methods in an abstract base class need to be pure virtual?

If an Abstract Class has derived class, they must implement all pure virtual functions, or else they will become Abstract too.

Can abstract class have non virtual function?

Abstract classes (apart from pure virtual functions) can have member variables, non-virtual functions, regular virtual functions, static functions, etc.

Which class has no pure virtual function?

A class is abstract if it has at least one pure virtual function. Unfortunately, there are cases when one cannot add a pure virtual method to a class to turn it in an abstract one and still he doesn't want users to be able to instantiate that class.


2 Answers

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. } 
like image 68
3 revs, 3 users 88% Avatar answered Sep 19 '22 03:09

3 revs, 3 users 88%


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. } 
like image 38
Nim Avatar answered Sep 20 '22 03:09

Nim