Making a copy of object from a pointer but dont know its type

Recommended Posts

BaneTrapper    1531

Hello.

In the main where i make a copy of above objects(bellow that comment) i don't know how to determinate what type the object it is so i wrote (a) for this example

[code]
class a
{
public:
virtual void Print();
};

class b : public a
{
public:
void Print();
};

class c : public a
{
public:
void Print();
};
//////////////////////////////////////////
void a::Print()
{
std::cout<<"a"<<std::endl;
}
void b::Print()
{
std::cout<<"b"<<std::endl;
}
void c::Print()
{
std::cout<<"c"<<std::endl;
}
//////////////////////////////////////////
int main()
{
std::unique_ptr<a> objA1 = std::unique_ptr<a>(new b);
std::unique_ptr<a> objA2 = std::unique_ptr<a>(new c);
//Make a copy of above objects
std::unique_ptr<a> objA3 = std::unique_ptr<a>(new a/*this a i do not know to to determinate its type*/(*objA1));
std::unique_ptr<a> objA4 = std::unique_ptr<a>(new a/*also this a i do not know to to determinate*/(*objA2));

objA1->Print();
objA2->Print();
objA3->Print();
objA4->Print();

system("pause");
return 0;
};
[/code]


Output is

b
c
a
a


But i need it to be (b c b c) how can i achieve that?

Share on other sites
BitMaster    8651
The general solution is to add a 'virtual a* clone() const' function and require that every subclass implements it correctly.

Share on other sites
Juliean    7068

You can even automate the process of defining the clone-methods by adding a intermedia templated class:

class a
{
public:

virtual a* Clone(void) = 0;
virtual void Print();
}

template<typename Class>
class a1 : public a
{
public:

a* Clone(void) const override final
{
return new Class(*this);
}
}

class b : public a1<b>
{
public:

void Print();
}

class c : public a1<c>
{
public:

void Print();
}


This can be usefull in reducing redundant code, since many/all implementations of clone will probably just call the classes copy-ctor in the first place, specially if you have many classes that derive from "a".

Share on other sites
BaneTrapper    1531

Ive bean reading true changes in c++11 and i think i will change the design not to use polymorphism in this part, thanks on help anywai.