I want to copy objects in c++. The problem is that i have derived classes with polymorphism, as shown i the pseudocode below:
class BaseCl { some virtual functions };
class DerivedClass : public BaseCl { ... };
...
BaseCl * b1 = new DerivedClass();
BaseCl * b2 = new "copy of b1"; (just pseudocode)
The problem is the last line:
I want to copy an object of the class "BaseCl", but because of the polymorphism the copy must be just like the original object of "DerivedClass".
What is the best way to do that?
Thank you very much, any help is appreciated.
Edit: Problem has been solved:
Inserted:
virtual BaseCl *clone() = 0;
in the base class and
DerivedCl *clone() {return new DerivedCl(*this);}
in the derived class. Thank you all.
You need to define a function in BaseC1 that makes a clone. Something like:
class BaseCl
{
virtual BaseCl* clone() {return new BaseC1(*this);}
};
class DerivedClass : public BaseCl
{
virtual BaseCl* clone() {return new DerivedClass(*this);}
};
The key of runtime polymorphism is that operations must be implemented in the most derived object, since it is the one than know everything it has to be known to perform them. All bases must expose virtual functions to be called by base pointers.
You can devine at the base level a virtual BaseCl* clone() function, and override it your derived classes to return new DerivedClass(*this)
Related
I searched around and seems in order to perform this I need to change my Base class and want to know if this is the best approach.
For example,
I have a Base class:
class Base {}
Then a long line of derived classes:
class Derived_1:: public Base {}
class Derived_2:: public Derived_1{}
...
...
class Derived_n:: public Derived_M{}
And then I have another class:
class DeepCopy
{
Base * basePtr;
public:
DeepCopy(DeepCopy & dc) {}
}
Assuming the Base class and Derived_x class copy constructors are properly coded, what is the best way to write the copy constructor for DeepCopy. How can we know about the class that is in the basePtr of the object we are going to copy?
Only way I can think of is using RTTI, but using a long list of dynamic_casts seems not right. Besides it requires DeepCopy to know about the inheritance hierarchy of Base class.
The other method I saw is here. But it requires Base and Derived classes implement a clone method.
So is there a much easier, standard way of doing this?
You need to use the virtual copy pattern: provide a virtual function in the interface that does the copy and then implement it across the hierarchy:
struct base {
virtual ~base() {} // Remember to provide a virtual destructor
virtual base* clone() const = 0;
};
struct derived : base {
virtual derived* clone() const {
return new derived(*this);
}
};
Then the DeepCopy object just needs to call that function:
class DeepCopy
{
Base * basePtr;
public:
DeepCopy(DeepCopy const & dc) // This should be `const`
: basePtr( dc.basePtr->clone() )
{}
};
Using an approach that employs a clone() function is a good solution. Note using the CRTP (the curiously recurring template pattern) can save you some of the work. The way you do it is by introducing an intermediate level (called BaseCRTP below) which is a template and implements the clone() function. When you derive your actual classes, use them as the template argument of the base they are derived from. They will get the clone() function implemented for them automatically. Make sure the derived classes implement a copy constructor (or be sure the default is what you need).
/* Base class includes pure virtual clone function */
class Base {
public:
virtual ~Base() {}
virtual Base *clone() const = 0;
};
/* Intermediate class that implements CRTP. Use this
* as a base class for any derived class that you want
* to have a clone function.
*/
template <typename Derived>
class BaseCRTP : public Base {
public:
virtual Base *clone() const {
return new Derived(static_cast<Derived const&>(*this));
}
};
/* Derive further classes. Each of them must
* implement a correct copy constructor, because
* that is used by the clone() function automatically.
*/
class Derived1 : public BaseCRTP<Derived1> {
/*... should have an ordinary copy constructor... */
};
class Derived2 : public BaseCRTP<Derived2> {
/*... should have an ordinary copy constructor... */
};
You can then obviously implement the DeepCopy class in the usual way:
class DeepCopy
{
Base *basePtr;
public:
DeepCopy(const DeepCopy &dc)
: basePtr(dc.basePtr->clone())
{}
};
I think that templates are the best way to go in this situation:
template<typename Sub>
class DeepCopy
{
Base *base;
DeepCopy(Sub *sub)
{
base = new Sub(*sub); // use copy constructor
}
}
This does mean that DeepCopy's are un-assignable to each other, but that's the price you pay with C++.
I have been struggling with this kind of problem for a long time, so I decided to ask here.
class Base {
virtual ~Base();
};
class Derived1 : public Base { ... };
class Derived2 : public Base { ... };
...
// Copies the instance of derived class pointed by the *base pointer
Base* CreateCopy(Base* base);
The method should return a dynamically created copy, or at least store the object on stack in some data structure to avoid "returning address of a temporary" problem.
The naive approach to implement the above method would be using multiple typeids or dynamic_casts in a series of if-statements to check for each possible derived type and then use the new operator.
Is there any other, better approach?
P.S.: I know, that the this problem can be avoided using smart pointers, but I am interested in the minimalistic approach, without a bunch of libraries.
You add a virtual Base* clone() const = 0; in your base class and implement it appropriately in your Derived classes. If your Base is not abstract, you can of course call its copy-constructor, but that's a bit dangerous: If you forget to implement it in a derived class, you'll get (probably unwanted) slicing.
If you don't want to duplicate that code, you can use the CRTP idiom to implement the function via a template:
template <class Derived>
class DerivationHelper : public Base
{
public:
virtual Base* clone() const
{
return new Derived(static_cast<const Derived&>(*this)); // call the copy ctor.
}
};
class Derived1 : public DerivationHelper <Derived1> { ... };
class Derived2 : public DerivationHelper <Derived2> { ... };
An alternative is to have a pure virtual CreateCopy() method in the common base that is implemented in each derived class.
I have a base class called Base which defines a virtual function. The class Derived now inherits from it and implements/overwrites that virtual function. The following code works just fine:
Base* pB = new Derived();
pB->virtual_function(); // function of class Derived gets called -> good
My problem is, that I now store all my derived instances in a STL container std::map<ID, Base*>. This seems to cause problems, because when I later iterate over that container and try for each Base* to call my virtual function, the runtime only recognizes the pointers as type Base* and does not call the overridden implementation in the class Derived.
Is there a way to get that working as intended or am I missing a crucial point here?
EDIT 1: Some additional code was requested, so here we go:
std::map<ComponentType, Base*> m_Components;
// The factory instantiates a Derived* (via functors) and returns it as Base*
Base* pB = m_pComponentFactory->createComponent(this, type);
// Lazy insert (since there is no map entry with key 'type' at that stage)
m_Components[type] = pB;
[...]
Base* pB;
for(ComponentMap::const_iterator it = m_Components.begin(); it != m_Components.end( ); ++it)
{
pB = it->second;
pB->virtual_function(); // goes to Base instead of Derived
}
EDIT 2: One thing I just realized is that I do not call dynamic_cast (or something similar) after creating the Derived instance via the functor (but I wouldn't know what to cast it to anyway since it is all generic/dynamic). It is just a return creator() with creator being the functor. Is that the issue?
Definition of creator type (the functon type):
typedef Base*(*ComponentCreator)([some params]);
Edit 3:
The actual functor is for example defined like this (Renderable and Location being derived classes from Base):
&Renderable::Create<Renderable> // or
&Location::Create<Location>
with the Create() method being a template function in the class Base.
template<typename T>
static Component* Create([some params])
{
return new T([some params]);
}
EDIT 4:
The problems seems to be my clone() + CopyConstructor handling. My clone currently looks like this:
Base* Base::clone() const
{
return new Base(*this);
}
Since I only create a Base*, the virtual resolution later on cannot work. The problem I am now left with though, is that I a missing an idea how to change the cloning. As shown in EDIT 1 I have my m_Components map with Base* pointers. I now need to clone them but I only know that they are of Base* and not of which exact derivative. One idea that comes to mind, might be to store functor used to create the Derived instance in the first place in the class, to reuse it later. So my clone would look something like this:
Base* Component::clone() const
{
return m_pCreationFunctor([some params]);
}
Anyone seeing a better approach?
You are a victim of slicing. When you copy construct a Base, you will lose the Derived parts of the object. See http://en.wikipedia.org/wiki/Object_slicing for a bit more detail. If the base class is not supposed to be instantiated, you might consider making it abstract to prevent making this mistake in future.
The fix in this case is probably to have a virtual Base * clone() method and override it in derived classes.
i.e.
class Base{
...
virtual Base * clone() const = 0;
...
};
class Derived : public Base {
...
Base * clone() const override { return new Derived(*this); }
...
};
If you really want to avoid rewriting the clone method, you could use an intermediate CRTP class i.e
struct Base{
virtual Base * clone() = 0;
};
template <typename D>
struct B : public Base {
virtual Base * clone() { return new D(*static_cast<D*>(this)); }
};
struct D : public B<D>{};
This has been bugging me lately. Say I have a base class Base. If I have multiple derived classes on top of Base, such as DerivedA and DerivedB, a deep copy gets to be a pain.
OtherClass(const OtherClass & _rhs)
{
//I have a list of Base *, now I must assign a class id to each derived class to properly create a new one.
//...
}
Is there any way to get around this?
You should define a clone method in your Base class:
virtual Base * clone() const = 0;
Each derived class implement that clone method:
virtual DerivedA * clone() const {
return new DerivedA(*this);
}
Then your OtherClass just has to iterate and call clone method over each instance of Base* in your list.
I have been struggling with this kind of problem for a long time, so I decided to ask here.
class Base {
virtual ~Base();
};
class Derived1 : public Base { ... };
class Derived2 : public Base { ... };
...
// Copies the instance of derived class pointed by the *base pointer
Base* CreateCopy(Base* base);
The method should return a dynamically created copy, or at least store the object on stack in some data structure to avoid "returning address of a temporary" problem.
The naive approach to implement the above method would be using multiple typeids or dynamic_casts in a series of if-statements to check for each possible derived type and then use the new operator.
Is there any other, better approach?
P.S.: I know, that the this problem can be avoided using smart pointers, but I am interested in the minimalistic approach, without a bunch of libraries.
You add a virtual Base* clone() const = 0; in your base class and implement it appropriately in your Derived classes. If your Base is not abstract, you can of course call its copy-constructor, but that's a bit dangerous: If you forget to implement it in a derived class, you'll get (probably unwanted) slicing.
If you don't want to duplicate that code, you can use the CRTP idiom to implement the function via a template:
template <class Derived>
class DerivationHelper : public Base
{
public:
virtual Base* clone() const
{
return new Derived(static_cast<const Derived&>(*this)); // call the copy ctor.
}
};
class Derived1 : public DerivationHelper <Derived1> { ... };
class Derived2 : public DerivationHelper <Derived2> { ... };
An alternative is to have a pure virtual CreateCopy() method in the common base that is implemented in each derived class.