Object Factory & cloning products

Started by
11 comments, last by Deliverance 16 years, 8 months ago
Quote:
Secondly, count the number of times you call new and count the number of times you call delete, they should always be equal, no exceptions, ever.

Lies! You should never call delete (that is to say, use smart pointers and other RAII objects that handle this muckery for you, they're better than you when it comes to this obnoxious tedium).

Quote:
The line *clonedProduct = *product; is not doing what it's supposed to do. Why is that?

You are doing static dispatch on the base type's overloaded operator; this is mangling your objects. The typical way the clone idiom is implemented involves calling a virtual clone method on the object, not the factory. In other words, the base class should have a pure-virtual clone() method implemented by all derived classes. The clone() method allocates a new derived type, initializes it based on the state of the invoking object, and returns the new object.

Your factory clone method can simply defer to this object clone method, like
template <class T>T* ObjectFactory<T>::CloneProduct(T* product){	  return product->clone();}


CGeometricObject would have a pure-virtual clone() method (virtual CGeometricObject* clone() const = 0;), and each child would implement it, perhaps, in the case of CSphere, as
class CSphere : public CGeometricObject{  public:    CSphere* clone() const // "covariant return types" allow the return type to be CSphere    {      CSphere *result = new CSphere(this->radius,this->position); // assuming CSphere has these...      return result;    }};
Advertisement
Quote:Original post by jpetrie
Quote:
Secondly, count the number of times you call new and count the number of times you call delete, they should always be equal, no exceptions, ever.

Lies. You should never call delete (that is to say, use smart pointers and other RAII objects that handle this muckery for you, they're better than you when it comes to this obnoxious tedium).

Appologies, I edited my post after noticing they were in-fact equal as I'd misread the clone function [rolleyes]
But yes, use RAII forever and always.

Anyway, as for the original problem, either go with the above design (better), or similarly you could make the operator= a virtual method within geometric object (same idea, but not as clear).
Thanks a lot!

This topic is closed to new replies.

Advertisement