C++ – Abstract Base Classes and Copy Construction Rules of Thumb

abstract classc

Often times it's a good idea to have an abstract base class to isolate the interface of the object.

The problem is that copy construction, IMHO, is pretty much broken by default in C++, with copy constructors being generated by default.

So, what are the gotchas when you have an abstract base class and raw pointers in derived classes?

class IAbstract
{
    ~IAbstract() = 0;
}

class Derived : public IAbstract
{
    char *theProblem;
    ...
}

IAbstract *a1 = new Derived();
IAbstract a2 = *a1;//???

And now do you cleanly disable copy construction for the whole hierarchy? Declare copy construction as private in IAbstract?

Are there any rules of three with abstract base classes?

Best Answer

Copy construction on an abstract class should be made private in most cases, as well as assignment operator.

Abstract classes are, by definition, made to be a polymorphic type. So you don't know how much memory your instance is using, and so cannot copy or assign it safely. In practice, you risk slicing : https://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c

Polymorphic type, in C++, mustn't be manipulated by value. You manipulate them by reference or by pointer (or any smart pointer).

This is the reason why Java has made object manipulable by reference only, and why C# and D has the separation between classes and structs (the first one being polymorphic and reference type, the second one being non polymorphic and value type).