Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

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

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.)

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