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

S

SzH

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;
};
 
I

IR

SzH said:
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; }
};
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,573
Members
45,046
Latest member
Gavizuho

Latest Threads

Top