Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding methods in C++

Sometimes I accidentally forget to call the superclass's method in C++ when I override a method.

Is there any way to help figure out when I'm overriding a method with, so that I don't forget to call the superclass's method? (Something like Java's @Override, except that C++ doesn't have annotations...)

like image 840
user541686 Avatar asked Feb 21 '23 21:02

user541686


2 Answers

One suggestion is the Non-Virtual Inferface Idiom. I.e., make your public methods non-virtual and have them call private or protected virtual methods that derived classes can override to implement their specific behavior.

If you don't have control over the base class, you could perhaps use an intermediate class:

class Foo // Don't control this one
{
  public:
    virtual void action();
};

class Bar : public Foo // Intermediate base class
{
  public:
    virtual void action()
    {
       doAction();
       Foo::action();
    }

  protected:
    virtual void doAction() = 0;
};

Derive your classes from Bar and override doAction() on each. You could even have doBeforeAction() and doAfterAction() if necessary.

like image 82
Fred Larson Avatar answered Mar 07 '23 06:03

Fred Larson


With regards to Java's @Override, there is a direct equivalent in C++11, namely the override special identifier.

Sadly, neither @Override nor override solve the problem since: (a) they're optional; (b) the responsibility of calling the base class's method still rests with the programmer.

Furthermore, I don't know of any widely available method that would address the problem (it's quite tricky, esp. given that you don't necessarily want to call the base class's method -- how is the machine to know?).

like image 21
NPE Avatar answered Mar 07 '23 05:03

NPE