oops, erratum, I forgot a virtual at the beginning of the duplicate declaration:
virtual A * duplicate() const = 0;
@coder777: the problem is that the duplicate() method must return a pointer to the class. This pointer have to be allocated by the final class (B or C) because it's the only one which knows its own type. That's why the duplicate() method from the class A can't be used to duplicate the data from A. I've changed my code, look at this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
class A
{
public:
A * duplicate() const = 0;
void internalDuplicate(const A & _src)
{
m_dataFromA = A.m_dataFromA;
}
int m_dataFromA;
};
class B : public A
{
public:
A * duplicate() const
{
B * b = new B;
b->internalDuplicate(*this);
b->m_dataFromB = m_dataFromB;
return b;
}
int m_dataFromB;
};
class C : public A
{
public:
A * duplicate() const
{
C * c = new C;
c->internalDuplicate(*this);
c->m_dataFromC = m_dataFromC;
return c;
}
int m_dataFromC;
};
|
This way, I refactored the duplication of A.
If you look at it from a higher level, the duplicate function aims the leaf class directly. And once called it get its way back to its parents classes.
It's the nicer way I found of doing it, is there a better one?
@sohguanh: I don't think so (it works on Visual at least, I'll try this on gcc later). Because the function needs a pointer to A, and B (or C) is inherited from A, the implicit cast is done seamlessly.