I have an inheritance hierarchy: class1 and class2 inherit from abstract class abstractClass. In my main program I create the following handle:
abstractClass * myPointer = new class1(parameter1);
myPointer could point to class2 object too. I will use myPointer for polymorphic calls. Now I have another class(we say class3) which uses composition and it has a member that is a pointer to abstractClass. Namely:
class class3
{
private:
abstractClass *ptr;
};
I want can do:
abstractClass * myPointer = new class1(parameter1);
class3 *myObject=new class3(myPointer);
like this, the class class3 has a pointer wherewith make polymorphic call. The problem is that i must do a deep copy, namely is bad do in the constructor of class3:
abstractClass * myPointer = new class1(parameter1);
class3 *myObject=new class3(myPointer);
class3::class3(abstractClass *pointer)
{
ptr = pointer; //ptr is the member of the class
}
I must do a deep copy. And I can't write
ptr = new Class1(.....)
or
ptr = new Class2()
because I don't know the type of object pointed from abstractClass *pointer. How can I do? (May be I must use the downcast and an if for understand the type of the object. But is there a more elegant solution?)
I use g++ -std=gnu++11 compiler
Thanks in advance