Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an abstract class be implemented without pure virtual functions in C++?

I thought of using protected constructor, but it couldn't completely solve the purpose since the class inheriting from it would be able to instantiate the base class.

As for private constructor, the derived classes too would not be instantiated.

So, any suitable technique would be appreciated.

like image 626
Sankalp Avatar asked Jul 03 '13 18:07

Sankalp


1 Answers

It is unclear what you are really asking for. So let me try to clear some points:

Pure virtual functions can have definitions

If your concern is that you want to provide definitions for all of the virtual functions in your base you can provide the definitions for the pure virtual functions, and they will be available for static dispatch.

Protected grants access to your base subobject, not to every instance of base

There is a common misconception that protected allows a particular derived type accessing any instance of base. That is not true. The keyword protected grants access to the base subobject within the derived type.

class base {
protected: base() {}
};
class derived : public base {
   derived() : base() {         // fine our subobject
      base b;                   // error, `b` is not your subobject
   }
};
like image 146
David Rodríguez - dribeas Avatar answered Sep 22 '22 14:09

David Rodríguez - dribeas