C++: Could Polymorphic Copy Constructors work?
c++, copy-constructor
Solution
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;
}
Problem
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?