Alex Rivera | Logout

When should a virtual method be pure?

Asked 2011-07-27T11:03:54.623
9

I have found some code that I am working on, and was wondering what the best design implementation is.

If a base class defines a method as virtual, but implements an empty body as well, thus not requiring the derived classes to implement a body, should it not be made pure instead?

virtual void AMethod1() {}                 // 1
virtual void AMethod2() {assert(false);}   // 2
virtual void AMethod3() = 0;               // 3
  1. Current code.
  2. Idea1: Alerts user that this derived object has not implemented this method body.
  3. Idea2: Forces derived classes to implement a body, empty or not.

What do you, the trusted amazing SO people, think?


Edit1: After posting (and reading answers), I realize that assert is bad!

virtual void AMethod3() = {throw (ENotImplemented)};               // 4
Edit
Report

3 Answers

2

Making method pure virtual is more intuitive than making default implementation with an assert. Current code is better if doing nothing is default implementation in most cases. Of course it should stay virtual if you want to use polymorphism.

answered 2011-07-27T11:11:44.103
2

I have seen quite a few examples like this where you need to instantiate the class, so you use virtual with a empty body:

virtual void AMethod1() {}                 // 1

Use this when you want to force the derived class to override this function and you don't need a default:

virtual void AMethod3() = 0;               // 3

So it really depends on what you want to do.

answered 2011-07-27T11:16:14.727
1

We should use pure virtual function if we do not want to instantiate a class but make it act as a base class for all the classes that derive from it.

An important thing to note about pure virtual functions is that these functions must be overridden in all the derived classes otherwise the compile would flag out an error.

Simple e.g,

class alpha     {
     public:virtual void show()=0; //pure virtual function
    };

class beta : public alpha {

     public:void show()   //overriding
        {
         cout<<"OOP in C++";
        }
    };
void main() {
     alpha *p;
     beta b;
     p=&b;
     p->show();
   }
answered 2011-07-27T11:06:29.103

Your Answer