Question

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?

Was it helpful?

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.

OTHER TIPS

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.

Old necro'd question, but one good way is to test early, either formally with unit tests, or more informally, before you start using your classes. In other words, check early on that:

A test_a;
B test_b;
A& poly_a = test_a;
A& poly_b = test_b;
assert(poly_a.longDescriptiveName() == 0);
assert(poly_b.longDescriptiveName() == 1);

before you write 10,000 more lines of code that use your classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top