views:

178

answers:

5

When creating a C++ inheritance structure, you have to define member functions exactly the same in multiple places:

If B is an abstract base class, and D, E, and F all inherit from B, you might have this:

class B
{
   virtual func A( ... params ) = 0;
};

class D : public B
{
   func A( ... params );
};

/* ... etc... similar implementations for E and F */

So, there is obviously some duplication here. If the interface to B is large, you may have many places to change if the interface needs to change.

A coworker suggested some trickery with an embedded craftily-created #includes, ala:

class D: public B
{
   #include "B_Interface.h"  // B_Interface.h is a specially crafted .h file
}

This seems a little kludgy? Is it? Is there a better solution to avoid dual maintenance?

Also, maybe the solution here is really better tools to support the language, like Visual Assist X?

Edit: Assume the derived classes must have unique implementations.

+1  A: 

If you have to implement them over and over with some default behavior then maybe they should just be virtual, and not pure virtual.

Chris H
In my particular case, there is a different implementation for each derived class.
Joe Schneider
+12  A: 

Actually, the biggest problem with changing an interface usually is all the code that uses it, not the code that implements it. If it's easy to change it for the implementer, it would probably make life harder for the users.

sbi
agreed -- IMHO and interface should be changed as little as possible so if it's a pain it's a good thing!
f4
+1  A: 

Instead of using the preprocessor for yet another way it should not be used I'd try my editor (or IDE, if that's what you fancy.)

pmr
+4  A: 

That it's painful to change a widely used interface is not a bug; it's a feature.

JohnMcG
+4  A: 

Also, maybe the solution here is really better tools to support the language, like Visual Assist X?

Exactly. Changing method signatures is a key feature of refactoring tools.

Ozan
I second the recommendation. If you have to refactor C++ code, I found VAX pretty good. (And I found it pretty good for many other reasons, too.)
sbi