Search code examples
c++virtual-functionsmisspelling

Detecting a misspelt virtual function


I've been caught by this problem more than once:

class A{
public:
  virtual ~A() {}
  virtual int longDescriptiveName(){ return 0; }
};

class B: public A{
public:
  virtual int longDescriptveName(){ return 1; } // Oops
};

If the function is pure virtual, the compiler catches the error. But if it's not this can be a terrible bug to track down. Part of the problem is that function names are maybe too long. But I still wonder, is there a way to see these bugs earlier?


Solution

  • One possibility is the little-used pure virtual function with implementation:

    virtual int longDescriptiveName() = 0
    {
        return 0; 
    }
    

    This forces deriving classes to override it. They can then call the base-class implementation alone if they only want that behaviour.

    Also you need to make sure your inheritance hierarchy is flat, rather than multi-layers, which is generally good anyway because inheritance is fragile enough without piling on the layers.