In C++, I find it very useful to add a "Clone()" method to classes that are part of hierarchies requiring (especially polymorphic) duplication with a signature like this:
class Foo {
public:
virtual Foo* Clone() const;
};
This may look pretty, but it is very prone to bugs introduced by class maintenance. Whenever anyone adds a data member to this class, they've got to remember to update the Clone() method. Failing to results in often subtle errors. Unit tests won't find the error unless they are updated or the class has an equality comparison method and that is both unit tested and was updated to compare the new member. Maintainers won't get a compiler error. The Clone() method looks generic and is easy to overlook.
Does anyone else have a problem with Clone() for this reason? I tend to put a comment in the class's header file reminding maintainers to update Clone if they add data members. Is there a better idea out there? Would it be silly/pedantic to insert a #if/etc. directives to look for a change to the class size and report a warning/error?
Why not just use the copy constructor?
virtual Foo* Clone() const { return new Foo(*this); }
Edit: Oh wait, is Foo the BASE class, rather than the DERIVED class? Same principle.
virtual Foo* Clone() const { return new MyFavouriteDerived(*this); }
Just ensure that all derived classes implement clone in this way, and you won't have a problem. Private copy constructor is no problem, because the method is a member and thus can access it.