Copy constructor for a class that contains a pointer to a base class type (newbie)

Discussion in 'C++' started by SzH, Oct 27, 2006.

  1. SzH

    SzH Guest

    This is a newbie question. Suppose I have a class A (see the attached
    code) which contains a pointer that can point to an object of either
    type D1 or D2. How do I write a copy constructor for A, so that the
    object that it references also gets copied (I don't know whether it is
    a D1 or D2 object)?

    Thank you for your answers in advance,
    Szabolcs

    ----

    class B {
    public:
    virtual void print() = 0;
    };

    class D1 : public B {
    int i;
    public:
    void print() { cout << i; }
    };

    class D2 : public B {
    double x;
    public:
    void print() { cout << x; }
    };

    class A {
    B *b;
    };
    SzH, Oct 27, 2006
    #1
    1. Advertising

  2. SzH

    IR Guest

    SzH wrote:
    > This is a newbie question. Suppose I have a class A (see the
    > attached code) which contains a pointer that can point to an
    > object of either type D1 or D2. How do I write a copy constructor
    > for A, so that the object that it references also gets copied (I
    > don't know whether it is a D1 or D2 object)?
    >
    > ----
    >
    > class B {
    > public:
    > virtual void print() = 0;
    > };
    >
    > class D1 : public B {
    > int i;
    > public:
    > void print() { cout << i; }
    > };
    >
    > class D2 : public B {
    > double x;
    > public:
    > void print() { cout << x; }
    > };
    >
    > class A {
    > B *b;
    > };


    AFAIK the only safe way to do this is having some kind of
    virtual B* Clone() method:

    class B {
    public:
    virtual B* Clone() = 0;
    virtual void print() = 0;
    };

    class D1 : public B {
    int i;
    public:
    virtual B* Clone() { return new D1(*this); };
    void print() { cout << i; }
    };

    class D2 : public B {
    double x;
    public:
    virtual B* Clone() { return new D2(*this); };
    void print() { cout << x; }
    };


    --
    IR
    IR, Oct 27, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. mrstephengross
    Replies:
    5
    Views:
    593
    Larry I Smith
    May 18, 2005
  2. =?ISO-8859-1?Q?Szabolcs_Horv=E1t?=
    Replies:
    4
    Views:
    491
    Daniel T.
    Oct 28, 2006
  3. ali
    Replies:
    4
    Views:
    568
    David Harmon
    Mar 5, 2007
  4. Rahul
    Replies:
    16
    Views:
    1,194
    terminator
    Nov 7, 2007
  5. cinsk
    Replies:
    35
    Views:
    2,590
    James Kanze
    Oct 11, 2010
Loading...

Share This Page