0

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

Nick
  • 1,439
  • 2
  • 15
  • 28
  • 4
    Make the abstractClass have a pure virtual call Clone() which both class1 and class2 implement and class3 will just call Clone() on the abstractClass. – Adrian Lis Apr 05 '17 at 15:49
  • What Adrian Lis is describing is commonly called the "Clone Idiom" if you wish to google it further. – Christopher Pisz Apr 05 '17 at 16:18

0 Answers0