views:

60

answers:

2

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?

+1  A: 

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.

Daniel Earwicker
+1  A: 

If you compile with Microsoft Visual C++ 2005 or newer, there is a non-standard extension allowing you to write:

virtual int longDescriptveName() override { return 1; }

And the compiler will complain. If you compile also with other compilers, its probably smart to make a #define so you can control the behavior.

jdv
That's useful extension! But I use gcc.
pythonic metaphor