Assume I have the following class-hierarchy in C++:
class AbstractBaseClass
{
public:
// Note: Class is completely abstract! No data!
AbstractBaseClass() {}
virtual ~AbstractBaseClass() {}
virtual std::string definedInVirtual() = 0;
virtual std::string definedInDerived() = 0;
};
class Virtual : public virtual AbstractBaseClass
{
public:
Virtual() {}
virtual ~Virtual() {}
std::string definedInVirtual()
{
return "definedInVirtual";
}
};
class DerivedA : public Virtual
{
public:
DerivedA() {}
virtual ~DerivedA() {}
std::string definedInDerived()
{
return "definedInDerivedA";
}
};
class DerivedB : public Virtual
{
public:
DerivedB() {}
virtual ~DerivedB() {}
std::string definedInDerived()
{
return "definedInDerivedB";
}
};
In this case, calling definedInVirtual() on either DerivedA or DerivedB, the definition of definedInVirtual() on Virtual is called, via cross-delegation. This is, then, a form of code reuse.
What are the drawbacks to this method? Is there a better way to achieve code reuse in this situation?
EDIT:
The main reason I ask is there was a very large class that someone had developed with the plan of code reuse via inheritance (he since regrets doing this, but the class is large) that was super-classed by a new ABC due to adding a decorator derived from the new ABC to the object hierarchy. I need to add methods to the new ABC that need to be handled by the DerivedA and DerivedB, and for the decorator to handle via calling the internal instance of the ABC. My idea is to use the above technique…
Code re-use should be implemented through composition, not inheritance. Virtual inheritance is slow and extremely messy and should be avoided in nearly all designs.