Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a body to a pure virtual/abstract function in C++?

A pure virtual function isn't supposed to have a body, but I just noticed that the following code is accepted by the compiler:

class foo
{
    virtual void dummy() = 0
    {
        cout << "hello";
    }
};

So, why are pure virtual functions allowed to have a body? Also, even when the function has a body, the class still can't be instantiated, why is that?

like image 263
Devesh Agrawal Avatar asked Feb 14 '23 14:02

Devesh Agrawal


2 Answers

Pure virtual function can have a body, but the fact that you declare them pure virtual is exactly to say that a derived implementation is required.

You can execute the pure virtual method from a derived method (using an explicit BaseClass::method()) but still you have to provide an implementation.

Not being able to instantiate a class with a pure virtual method that has not been overriden is the main point of the pure virtual declaration. In other words the idea of declaring a method pure virtual is to ensure that the programmer will not forget about providing its implementation.

like image 121
6502 Avatar answered Feb 24 '23 00:02

6502


Generally speaking, abstract class is used to define interface and/or partial implementation, and is intended to be inherited by concrete classes. It is a way of enforcing a contract between class designer and users of that class, whatever they are.

If you don't need this contract and want instantiation, then do not enforce it to be abstract class, i.e. remove = 0.

If your concern is why would pure virtual functions have body in the first place, then one good example could be this quote from the Effective C++ book by Scott Meyers:

Derived classes that implement this pure virtual function may call this implementation somewhere in their code. If part of the code of two different derived classes is similar then it makes sense to move it up in the hierarchy, even if the function should be pure virtual.

Another example is pure virtual destructor (which is also a function by the way):

...

virtual ~foo() = 0;

...

foo::~foo() {} // required!

when you are required to provide implementation for it, but at the same time want to make it pure virtual in order to make the foo class abstract. So, in fact, the core of the language itself relies on this feature.

like image 23
Alexander Shukaev Avatar answered Feb 24 '23 00:02

Alexander Shukaev