   [C++] Inheritance-related problem
  Hello!I have a problem in my application. I need to clone an object of which I only know the base class. Here's the context :class foo{CBaseClass * obj;foo(CBaseClass * o){  // make a copy of "o" for the "obj" pointer... how?}};I cannot just make a new CBaseClass because "o" might be a CDerivedClass...Put simply, I need to clone a class without knowing if it is a base class or a derived class.How do I do?   
  make a virtual clone function in the base class which you override in the child.class base{public:  virtual base* clone() const { return new base( *this ); }  virtual ~base {}};class child{public:  child* clone() const { return new child( *this ); }};class foo{public:  foo( base const* bar_init )    : bar_m( bar_init ? bar_init->clone() : 0 )  {  }  // Define copy constructor, assignment, destructor, etc.private:  base* bar_m; // prefer a smart pointer here};;  You'll need to have a virtual function which each class overrides to make a copy of itself:class CBaseClass{public:   CBaseClass() { /* Default constructor */ }   CBaseClass(const CBaseClass& rhs) { /* Copy constructor */ }   virtual ~CBaseClass() {}   virtual CBaseClass* Copy()   { return new CBaseClass(*this);   }}class CDerived : public CBaseClass{public:   CDerived() { /* Default constructor */ }   CDerived(const CDerived& rhs) : CBaseClass(rhs) { /* Copy constructor */ }   virtual ~CDerived() {}   virtual CDerived* Copy()   { return new CDerived(*this);   }};class foo{CBaseClass* obj;   foo(CBaseClass* o)   {obj = o->Copy();   }};I think that'll work anyway, I haven't tested it.EDIT: Bah, too slow.EDIT 2: And mine isn't const. Oh well, I lose...   ;Quote:Original post by TrillianHow do I do?Typically, I see this accomplished with the cloning technique.CBaseClass implements a function "virtual CBaseClass * clone() const;" which returns a new copy of itself.  Derived classes then need to override this function to return a new instance of themselves.  Your code would then become:class foo{    CBaseClass * obj;    foo(CBaseClass * o)    {   obj = o->clone();    }};;  Thank you all for your tips, I'm going to apply it right now!   ;class CBaseClass{public:    virtual CBaseClass* Clone( ) { return new CBaseClass; }};class CDerivedClass : public CBaseClass{public:    virtual CBaseClass* Clone( ) { return new CDerivedClass; }};;  Yep. Should go in the FAQ then, eh? :)This is one of the regrettable limits of the C++ language WRT its OO support.Note that the same technique is sometimes used for default-construction, instead of (or in addition to) copy-construction. I'm not sure why you'd want to "copy the type" of another object but not its data; but presumably it comes up every now and then.You can read more here, but it's basically more of the same. :P   