Consider:
class A
{
public:
A( int val ) : m_ValA( val ) {}
A( const A& rhs ) {}
int m_ValA;
};
class B : public A
{
public:
B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {}
B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {}
int m_ValB;
};
int main()
{
A* b1 = new B( 1, 2 );
A* b2 = new A( *b1 ); // ERROR...but what if it could work?
return 0;
}
Would C++ be broken if "new A( b1 )" was able to resolve to creating a new B copy and returning an A?
Would this even be useful?
Do you need this functionality, or is this just a thought experiment?
If you need to do this, the common idiom is to have a Clone
method:
class A
{
public:
A( int val ) : m_ValA( val ) {}
A( const A& rhs ) {}
virtual A *Clone () = 0;
int m_ValA;
};
class B : public A
{
public:
B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {}
B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {}
A *Clone() { return new B(*this); }
int m_ValB;
};
int main()
{
A* b1 = new B( 1, 2 );
A* b2 = b1->Clone();
return 0;
}
What you're really looking for is called a virtual copy constructor, and what eduffy posted is the standard way of doing it.
There are also clever ways of doing it with templates. (disclaimer: self-promotion)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With