Here is the problem, I have a vector of pointers to an abstract base class filled with derived objects like so:
class AbstractBase { /* ... */ };
clase Derived1 : public AbstractBase {
Derived1() { }
Derived1( const AbstractBase& abc ) { /* ... */ }
};
/* ... */
vector< AbstratcBase* > lThingies;
const AbstractBase& getThingie(int pos) {
return *lThingies[pos];
}
And to get copies of the elements I use the derived class “copy constructor” like so:
Derived1 d1 = getThingie(2);
But the problem is that I don’t like this: There is no way to force the implementation of this “copy constructor” when building the class “derived42” and even when you do remember it’s very easy to get it wrong (like making it a recursive call, happened to me).
My question is: Is there a better way to do this? how?
Update:
One of the “unwritten” requirements of the solution that I’m looking for is to get a copy of the derived object as a local variable, so I don’t forget to delete it.
More info:
There are a number of lThingies and, at runtime, I can tell what are the derived objects contained within (derived1, derived2, etc.), but not at compile time.
Do you know your
getThingiereturns aDerived1? If you know this, possibly you should change the return type ofDerived1and the storage in thestd::vectorto beDerived1instead ofAbstractBase.Assuming the above doesn’t work, you can do a
Derived1 bob = dynamic_cast<Derived1&>(getThingie(...));, which does a run-time check that the thingy is aDerived1or more derived instance, and if so it does the cast — if not, it throws an exception.If you don’t want to bother with the run time check because you are so certain that it is a
Derived1, simply useDerived1 bob = static_cast<Derived1&>(getThingy(...));.However, working with actual instances of classes which have an inheritance hierarchy is very questionable. There are many, many things that can go wrong.