I have base-class Base from which is derived Derived1, Derived2 and Derived3.
I have constructed an instance for one of the the derived classes which I store as Base* a. I now need to make a deep copy of the object which I will store as Base* b.
As far as I know, the normal way of copying a class is to use copy constructors and to overload operator=. However since I don't know whether a is of type Derived1, Derived2 or Derived3, I cannot think of a way of using either the copy constructor or operator=. The only way I can think of to cleanly make this work is to implement something like:
class Base
{
public:
virtual Base* Clone() = 0;
};
and the implement Clone in in the derived class as in:
class Derivedn : public Base
{
public:
Base* Clone()
{
Derived1* ret = new Derived1;
copy all the data members
}
};
Java tends to use Clone quite a bit is there more of a C++ way of doing this?
This is still how we do stuff in C++ for polymorphic classes, but you don't need to do the explicit copy of members if you create a copy constructor (possibly implicit or private) for your objects.
class Base
{
public:
virtual Base* Clone() = 0;
};
class Derivedn : public Base
{
public:
//This is OK, its called covariant return type.
Derivedn* Clone()
{
return new Derivedn(*this);
}
private:
Derivedn(const Derivedn&) : ... {}
};
template <class T>
Base* Clone (T derivedobj) {
T* derivedptr = new T(derivedobj);
Base* baseptr = dynamic_cast<Base*>(derivedptr);
if(baseptr != NULL) {
return baseptr;
}
// this will be reached if T is not derived from Base
delete derivedptr;
throw std::string("Invalid type given to Clone");
}
The only thing this function requires of the derived classes is that their copy constructor is publicly accessible.
I have seen some answers using a template function to clone objects. Let me show you how that will not work. Consider the following code:
This is a special case that shows up when objects are being received from a container of Base objects. The function will return a pointer to the Base even when obj is of type Derived. The template only works when it is called by an object that has not undergone any casting.
#include <iostream>
#include <memory>
#include <vector>
class Base{
public:
virtual void foo(){}
};
class Derived : public Base{};
template<typename T> std::shared_ptr<T> foo(const T& obj){
std::cout << "obj is of type: " << typeid(obj).name() << std::endl;
std::cout << "T is of type: " << typeid(T).name() << std::endl;
std::cout << std::endl;
return std::make_shared<T>(obj); // returns Base pointer
}
int main()
{
std::vector<std::shared_ptr<Base>> vec {std::make_shared<Base>(), std::make_shared<Derived>()};
for(auto c: vec)
foo(*c);
return 0;
}
/* OUTPUT:
obj is of type: 4Base
T is of type: 4Base
obj is of type: 7Derived
T is of type: 4Base
*/
Related
I have base-class Base from which is derived Derived1, Derived2 and Derived3.
I have constructed an instance for one of the the derived classes which I store as Base* a. I now need to make a deep copy of the object which I will store as Base* b.
As far as I know, the normal way of copying a class is to use copy constructors and to overload operator=. However since I don't know whether a is of type Derived1, Derived2 or Derived3, I cannot think of a way of using either the copy constructor or operator=. The only way I can think of to cleanly make this work is to implement something like:
class Base
{
public:
virtual Base* Clone() = 0;
};
and the implement Clone in in the derived class as in:
class Derivedn : public Base
{
public:
Base* Clone()
{
Derived1* ret = new Derived1;
copy all the data members
}
};
Java tends to use Clone quite a bit is there more of a C++ way of doing this?
This is still how we do stuff in C++ for polymorphic classes, but you don't need to do the explicit copy of members if you create a copy constructor (possibly implicit or private) for your objects.
class Base
{
public:
virtual Base* Clone() = 0;
};
class Derivedn : public Base
{
public:
//This is OK, its called covariant return type.
Derivedn* Clone()
{
return new Derivedn(*this);
}
private:
Derivedn(const Derivedn&) : ... {}
};
template <class T>
Base* Clone (T derivedobj) {
T* derivedptr = new T(derivedobj);
Base* baseptr = dynamic_cast<Base*>(derivedptr);
if(baseptr != NULL) {
return baseptr;
}
// this will be reached if T is not derived from Base
delete derivedptr;
throw std::string("Invalid type given to Clone");
}
The only thing this function requires of the derived classes is that their copy constructor is publicly accessible.
I have seen some answers using a template function to clone objects. Let me show you how that will not work. Consider the following code:
This is a special case that shows up when objects are being received from a container of Base objects. The function will return a pointer to the Base even when obj is of type Derived. The template only works when it is called by an object that has not undergone any casting.
#include <iostream>
#include <memory>
#include <vector>
class Base{
public:
virtual void foo(){}
};
class Derived : public Base{};
template<typename T> std::shared_ptr<T> foo(const T& obj){
std::cout << "obj is of type: " << typeid(obj).name() << std::endl;
std::cout << "T is of type: " << typeid(T).name() << std::endl;
std::cout << std::endl;
return std::make_shared<T>(obj); // returns Base pointer
}
int main()
{
std::vector<std::shared_ptr<Base>> vec {std::make_shared<Base>(), std::make_shared<Derived>()};
for(auto c: vec)
foo(*c);
return 0;
}
/* OUTPUT:
obj is of type: 4Base
T is of type: 4Base
obj is of type: 7Derived
T is of type: 4Base
*/
I have a class with a vector as below:
#include <vector>
class Base{};
class Derived: public Base{};
class Foo{
private:
std::vector<Base*> vec;
public:
Foo() = default;
void addObject(const Base* b){
// vec.push_back(new Base(*b));
// vec.push_back(new Derived(*b));
}
};
int main(){
Derived* d = new Derived();
Base* b = new Base();
Foo f;
f.addObject(d);
f.addObject(b);
delete d;
delete b;
return 0;
}
The function addBase may receive Derived's pointers. The line vec.push_back(new Base(b)); is expected to use b's copy to initialize a new object whose pointer will be pushed_back. If I don't use new, I will have resources shared between b and the vector(This is a sin).
I want to maintain polymorphism. How do I ensure objects that are pushed back maintain the type they were assigned during their creation without forcing everything into a Base object.
If you want to create a clone of the object passed to addObject, you have essentially two options. 1) Have a virtual function clone in Base and Derived, or better 2) let the copy constructor handle it.
If you go for the second option, addObject need to the know the actual type of the passed object. This could be done with a template:
template <class T>
void addObject(const T * t)
{
Base *b = new T(*t);
}
In a robust program we don't want to use new/delete but rather std::unique_ptr or std::shared_ptr. Passing t as a reference, rater than pointer, is also considered a better practice.
#include <vector>
#include <memory>
#include <iostream>
class Base
{
public:
virtual void cname() { std::cout << "Base" << std::endl;}
};
class Derived: public Base
{
public:
virtual void cname() { std::cout << "Derived" << std::endl;}
};
class Foo
{
private:
// You may switch to `std::shared_ptr` if that better fits your use case
std::vector<std::unique_ptr<Base> > vec;
public:
template <class T>
void addObject(const T & t)
{
vec.push_back(std::make_unique<T> (t));
}
void dump()
{
for (auto &bp: vec)
bp->cname();
}
};
int main(){
Derived d;
Base b;
Foo f;
f.addObject(d);
f.addObject(b);
f.dump();
return 0;
}
Naturally for this to work, the reference passed to addObject must be of the correct type. This will create a clone of type Base, not Derived:
Derived d;
Base &e = d;
f.addObject(e);
In our legacy project we have a function that takes reference to a base class and creates a copy of the derived class on the heap. This is solved essentially like this: https://godbolt.org/z/9ooM4x
#include <iostream>
class Base
{
public:
virtual Base* vclone() const = 0;
int a{7};
};
class Derived : public Base
{
public:
Derived()
{
a = 8;
}
Base* vclone() const override
{
return new Derived(*this);
}
};
Base* clone(const Base& original)
{
return original.vclone();
}
int main()
{
Derived d1;;
auto* d2 = clone(d1);
std::cout << d2->a << std::endl;
}
This works, but I would like to get rid of the boilerplate vclone method that we have to have in every single derived class.
We have hundreds of derived classes, some of them derived not directly from Base, but from some of the other derived classes too. So if we forget to override the vclone method, we may not even get a warning of the slicing that will happen.
Now, there is much to say about such a design, but this is 10-15 year old code that I try to modernize step by step. What I do look for, is a templatized version of clone that does not depend on a virtual method. What I want, is a clone function like this:
Base* clone(const Base& original)
{
return new <Actual Derived Type>(original);
}
The actual derived type is somewhat known, since a dynamic_cast will fail if trying to cast to it with wrong type, but I don't know if it is possible to access the actual type in a way that I want.
Any help would be appreciated.
I also think you probably cannot improve the code in the sense to make it shorter.
I would say this implementation is basically the way to go.
What you could do is to change the return value of Derived::clone to Derived *. Yes C++ allows this.
Then a direct use of Derived::clone yields the correct pointer type and Base::clone still works as expected
class Derived : public Base
{
public:
Derived()
{
a = 8;
}
Derived* vclone() const override // <<--- 'Derived' instead of 'Base'.
{
return new Derived(*this);
}
};
I would also rename to vclone member function to clone (There is no need to have two names).
The free function clone could be made a template so that it works for all classes and returns the right pointer type
template <class T>
T *clone(const T *cls)
{
return cls->clone();
}
However, all these changes do not make the code shorter, just more usable and perhaps more readable.
To make it a little shorter you might use an CRTP approach.
template <class Derived, class Base>
class CloneHelper: public Base {
Derived* vclone() const override
{
return new Derived(* static_cast<Derived *>(this) );
}
};
// then use
class Derived : public CloneHelper<Derived, Base>
{
public:
Derived()
{
a = 8;
}
};
However, I am not sure if it is worth it. One still must not forget the CloneHelper, it makes inheritance always public and you cannot delegate to the Base constructor so easily and it is less explicit.
You could use an outside clone function and typeid:
#include <typeindex>
#include <string>
#include <stdexcept>
#include <cassert>
template<class Derived_t, class Base_t>
Base_t *clone_helper(Base_t *b) {
return new Derived_t(*static_cast<Derived_t *>(b));
}
struct Base {
virtual ~Base() = default;
};
struct Derived : Base {};
Base *clone(Base *b) {
const auto &type = typeid(*b);
if (type == typeid(Base)) {
return clone_helper<Base>(b);
}
if (type == typeid(Derived)) {
return clone_helper<Derived>(b);
}
throw std::domain_error(std::string("No cloning provided for type ") + typeid(*b).name());
}
int main() {
Derived d;
Base *ptr = &d;
auto ptr2 = clone(ptr);
assert(typeid(*ptr2) == typeid(Derived));
}
This will find at runtime if you did not provide a clone method. It may be slower than usual. Sadly a switch is not possible since we cannot obtain the typeid of a type at compile time.
You may like to implement clone function in a separate class template, which is only applied to derived classes when an object of a derived class is created. The derived classes do not implement clone (keep it pure virtual) to avoid forgetting to override it in a further derived class.
Example:
struct Base {
virtual Base* clone() const = 0;
virtual ~Base() noexcept = default;
};
template<class Derived>
struct CloneImpl final : Derived {
using Derived::Derived;
CloneImpl* clone() const override { // Covariant return type.
return new CloneImpl(*this);
}
};
template<class T>
std::unique_ptr<T> clone(T const& t) { // unique_ptr to avoid leaks.
return std::unique_ptr<T>(t.clone());
}
struct Derived : Base {};
struct Derived2 : Derived {};
int main() {
CloneImpl<Derived> d1; // Apply CloneImpl to Derived when creating an object.
auto d2 = clone(d1);
auto d3 = clone(*d2);
CloneImpl<Derived2> c1; // Apply CloneImpl to Derived2 when creating an object.
auto c2 = clone(c1);
auto c3 = clone(*c2);
}
See https://stackoverflow.com/a/16648036/412080 for more details about implementing interface hierarchies without code duplication.
I have base-class Base from which is derived Derived1, Derived2 and Derived3.
I have constructed an instance for one of the the derived classes which I store as Base* a. I now need to make a deep copy of the object which I will store as Base* b.
As far as I know, the normal way of copying a class is to use copy constructors and to overload operator=. However since I don't know whether a is of type Derived1, Derived2 or Derived3, I cannot think of a way of using either the copy constructor or operator=. The only way I can think of to cleanly make this work is to implement something like:
class Base
{
public:
virtual Base* Clone() = 0;
};
and the implement Clone in in the derived class as in:
class Derivedn : public Base
{
public:
Base* Clone()
{
Derived1* ret = new Derived1;
copy all the data members
}
};
Java tends to use Clone quite a bit is there more of a C++ way of doing this?
This is still how we do stuff in C++ for polymorphic classes, but you don't need to do the explicit copy of members if you create a copy constructor (possibly implicit or private) for your objects.
class Base
{
public:
virtual Base* Clone() = 0;
};
class Derivedn : public Base
{
public:
//This is OK, its called covariant return type.
Derivedn* Clone()
{
return new Derivedn(*this);
}
private:
Derivedn(const Derivedn&) : ... {}
};
template <class T>
Base* Clone (T derivedobj) {
T* derivedptr = new T(derivedobj);
Base* baseptr = dynamic_cast<Base*>(derivedptr);
if(baseptr != NULL) {
return baseptr;
}
// this will be reached if T is not derived from Base
delete derivedptr;
throw std::string("Invalid type given to Clone");
}
The only thing this function requires of the derived classes is that their copy constructor is publicly accessible.
I have seen some answers using a template function to clone objects. Let me show you how that will not work. Consider the following code:
This is a special case that shows up when objects are being received from a container of Base objects. The function will return a pointer to the Base even when obj is of type Derived. The template only works when it is called by an object that has not undergone any casting.
#include <iostream>
#include <memory>
#include <vector>
class Base{
public:
virtual void foo(){}
};
class Derived : public Base{};
template<typename T> std::shared_ptr<T> foo(const T& obj){
std::cout << "obj is of type: " << typeid(obj).name() << std::endl;
std::cout << "T is of type: " << typeid(T).name() << std::endl;
std::cout << std::endl;
return std::make_shared<T>(obj); // returns Base pointer
}
int main()
{
std::vector<std::shared_ptr<Base>> vec {std::make_shared<Base>(), std::make_shared<Derived>()};
for(auto c: vec)
foo(*c);
return 0;
}
/* OUTPUT:
obj is of type: 4Base
T is of type: 4Base
obj is of type: 7Derived
T is of type: 4Base
*/
In C++, is there any way to query the type of an object and then use that information to dynamically create a new object of the same type?
For example, say I have a simple 3 class hierarchy:
class Base
class Foo : public Base
class Bar : public Base
Now suppose I give you an object cast as type Base -- which is in reality of type Foo.
Is there a way to query the type and use that info to later create new objects of type Foo?
Clone method
There is nothing provided by the language that queries type and lets you construct from that information, but you can provide the capability for your class hierarchy in various ways, the easiest of which is to use a virtual method:
struct Base {
virtual ~Base();
virtual std::auto_ptr<Base> clone(/*desired parameters, if any*/) const = 0;
};
This does something slightly different: clone the current object. This is often what you want, and allows you to keep objects around as templates, which you then clone and modify as desired.
Expanding on Tronic, you can even generate the clone function.
Why auto_ptr? So you can use new to allocate the object, make the transfer of ownership explicit, and the caller has no doubt that delete must deallocate it. For example:
Base& obj = *ptr_to_some_derived;
{ // since you can get a raw pointer, you have not committed to anything
// except that you might have to type ".release()"
Base* must_free_me = obj.clone().release();
delete must_free_me;
}
{ // smart pointer types can automatically work with auto_ptr
// (of course not all do, you can still use release() for them)
boost::shared_ptr<Base> p1 (obj.clone());
auto_ptr<Base> p2 (obj.clone());
other_smart_ptr<Base> p3 (obj.clone().release());
}
{ // automatically clean up temporary clones
// not needed often, but impossible without returning a smart pointer
obj.clone()->do_something();
}
Object factory
If you'd prefer to do exactly as you asked and get a factory that can be used independently of instances:
struct Factory {}; // give this type an ability to make your objects
struct Base {
virtual ~Base();
virtual Factory get_factory() const = 0; // implement in each derived class
// to return a factory that can make the derived class
// you may want to use a return type of std::auto_ptr<Factory> too, and
// then use Factory as a base class
};
Much of the same logic and functionality can be used as for a clone method, as get_factory fulfills half of the same role, and the return type (and its meaning) is the only difference.
I've also covered factories a couple times already. You could adapt my SimpleFactory class so your factory object (returned by get_factory) held a reference to a global factory plus the parameters to pass to create (e.g. the class's registered name—consider how to apply boost::function and boost::bind to make this easy to use).
The commonly used way to create copies of objects by base class is adding a clone method, which is essentially a polymorphic copy constructor. This virtual function normally needs to be defined in every derived class, but you can avoid some copy&paste by using the Curiously Recurring Template Pattern:
// Base class has a pure virtual function for cloning
class Shape {
public:
virtual ~Shape() {} // Polymorphic destructor to allow deletion via Shape*
virtual Shape* clone() const = 0; // Polymorphic copy constructor
};
// This CRTP class implements clone() for Derived
template <typename Derived> class Shape_CRTP: public Shape {
public:
Shape* clone() const {
return new Derived(dynamic_cast<Derived const&>(*this));
}
};
// Every derived class inherits from Shape_CRTP instead of Shape
// Note: clone() needs not to be defined in each
class Square: public Shape_CRTP<Square> {};
class Circle: public Shape_CRTP<Circle> {};
// Now you can clone shapes:
int main() {
Shape* s = new Square();
Shape* s2 = s->clone();
delete s2;
delete s;
}
Notice that you can use the same CRTP class for any functionality that would be the same in every derived class but that requires knowledge of the derived type. There are many other uses for this besides clone(), e.g. double dispatch.
There's only some hacky ways to do this.
The first and IMHO the ugliest is:
Base * newObjectOfSameType( Base * b )
{
if( dynamic_cast<Foo*>( b ) ) return new Foo;
if( dynamic_cast<Bar*>( b ) ) return new Bar;
}
Note that this will only work if you have RTTI enabled and Base contains some virtual function.
The second an neater version is to add a pure virtual clone function to the base class
struct Base { virtual Base* clone() const=0; }
struct Foo : public Base { Foo* clone() const { return new Foo(*this); }
struct Bar : public Base { Bar* clone() const { return new Bar(*this); }
Base * newObjectOfSameType( Base * b )
{
return b->clone();
}
This is much neater.
One cool/interesting thing about this is that
Foo::clone returns a Foo*, while Bar::clone returns a Bar*. You might expect this to break things, but everything works due to a feature of C++ called covariant return types.
Unfortunately covariant return types don't work for smart pointers, so using sharted_ptrs your code would look like this.
struct Base { virtual shared_ptr<Base> clone() const=0; }
struct Foo : public Base { shared_ptr<Base> clone() const { return shared_ptr<Base>(new Foo(*this) ); }
struct Bar : public Base { shared_ptr<Base> clone() const { return shared_ptr<Base>(new Bar(*this)); }
shared_ptr<Base> newObjectOfSameType( shared_ptr<Base> b )
{
return b->clone();
}
You can use e.g. typeid to query an object's dynamic type, but I don't know of a way to directly instantiate a new object from the type information.
However, apart from the clone approach mentioned above, you could use a factory:
#include <typeinfo>
#include <iostream>
class Base
{
public:
virtual void foo() const
{
std::cout << "Base object instantiated." << std::endl;
}
};
class Derived : public Base
{
public:
virtual void foo() const
{
std::cout << "Derived object instantiated." << std::endl;
}
};
class Factory
{
public:
static Base* createFrom( const Base* x )
{
if ( typeid(*x) == typeid(Base) )
{
return new Base;
}
else if ( typeid(*x) == typeid(Derived) )
{
return new Derived;
}
else
{
return 0;
}
}
};
int main( int argc, char* argv[] )
{
Base* X = new Derived;
if ( X != 0 )
{
std::cout << "X says: " << std::endl;
X->foo();
}
Base* Y = Factory::createFrom( X );
if ( Y != 0 )
{
std::cout << "Y says: " << std::endl;
Y->foo();
}
return 0;
}
P.S.: The essential part of this code example is of course the Factory::createFrom method. (It's probably not the most beautiful C++ code, since my C++ has gone a little rusty. The factory method probably shouldn't be static, on second thought.)
I used macros in my project to synthesize such methods.
I'm just researching this approach now, so I may be wrong, but here's an answer to your question in my code of IAllocable.hh. Note that I use GCC 4.8, but I hope 4.7 suits.
#define SYNTHESIZE_I_ALLOCABLE \
public: \
auto alloc() -> __typeof__(this) { return new (__typeof__(*this))(); } \
IAllocable * __IAllocable_alloc() { return new (__typeof__(*this))(); } \
private:
class IAllocable {
public:
IAllocable * alloc() {
return __IAllocable_alloc();
}
protected:
virtual IAllocable * __IAllocable_alloc() = 0;
};
Usage:
class Usage : public virtual IAllocable {
SYNTHESIZE_I_ALLOCABLE
public:
void print() {
printf("Hello, world!\n");
}
};
int main() {
{
Usage *a = new Usage;
Usage *b = a->alloc();
b->print();
delete a;
delete b;
}
{
IAllocable *a = new Usage;
Usage *b = dynamic_cast<Usage *>(a->alloc());
b->print();
delete a;
delete b;
}
}
Hope it helps.
In C++, is there any way to query the type of an object...
Yes, use typeid() operator
For example:
// typeid, polymorphic class
#include <iostream>
#include <typeinfo>
#include <exception>
using namespace std;
class CBase { virtual void f(){} };
class CDerived : public CBase {};
int main () {
try {
CBase* a = new CBase;
CBase* b = new CDerived;
cout << "a is: " << typeid(a).name() << '\n';
cout << "b is: " << typeid(b).name() << '\n';
cout << "*a is: " << typeid(*a).name() << '\n';
cout << "*b is: " << typeid(*b).name() << '\n';
} catch (exception& e) { cout << "Exception: " << e.what() << endl; }
return 0;
}
Output:
a is: class CBase *
b is: class CBase *
*a is: class CBase
*b is: class CDerived
If the type typeid evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid exception
Read more.....
class Base
{
public:
virtual ~Base() { }
};
class Foo : public Base
{
};
class Bar : public Base
{
};
template<typename T1, typename T2>
T1* fun(T1* obj)
{
T2* temp = new T2();
return temp;
}
int main()
{
Base* b = new Foo();
fun<Base,Foo>(b);
}
When there are extremely many classes deriving from the same base class then this code will save you from having to include clone methods every class. It's a more convenient way of cloning that involves templates and an intermediate subclass. It's doable if the hierarchy is shallow enough.
struct PureBase {
virtual Base* Clone() {
return nullptr;
};
};
template<typename T>
struct Base : PureBase {
virtual Base* Clone() {
return new T();
}
};
struct Derived : Base<Derived> {};
int main() {
PureBase* a = new Derived();
PureBase* b = a->Clone(); // typeid(*b) == typeid(Derived)
}