TheNotMe TheNotMe - 1 month ago 13
C++ Question

Copy constructors and inheritance

I have three classes.

class A
{
private:
int num;
//...
// THIS IS AN ABSTRACT CLASS (has a pure virtual function)
}

class B : public A
{
private:
float fnum;
//...
}

class C : public A
{
private:
double dnum;
//...
}


Now, I have a function

foo(A& someA)


and in it I would like to initialize an
A*
object according to its' type (
B
or
C
). This
A
can be originally a
B
or a
C


How can I do that using copy constructors? I have something like this:

A* newA = A.isB ? new B(someA) : new C(someA)


and I have added the copy constructors as such:

B(const B& b) : A(b) { fnum = b.fnum; }
C(const C& c) : A(c) { dnum = c.dnum; }


But this of course throws an error in the line

A* newA = A.isB ? new B(someA) : new C(someA)


that there is no suitable constructor.

Answer

The simple solution is:

A* newA = A.isB ? new B(dynamic_cast<const B&>(someA)) : 
                  new C(dynamic_cast<const C&>(someA));

A cleaner solution is to declare:

virtual A* clone() const = 0;

in A, and then creating newA is just:

A* newA = someA.clone();

Each derived class, write:

A* B::clone() const {
    return new B(*this);
}

But beware: if you derive a class from B, you will need to reimplement clone, and the compiler won't warn if you don't.

Comments