If you only have a pointer to Shape , then you cannot make a copy of the actual implementation - it (most likely) will be larger, so your copy will be "sliced". In your example, Circle will have an extra int a ; which is not part of the Shape class, which will be lost if you simply copy an object of the Shape class without knowing its Circle (and the whole point of polymorphism is that you do not have to āknowā which object is a type when working with it in general features "
To avoid problems caused by accidental use of something like:
*q = *p;
itās better to ādeleteā statements that allow you to do this
However, since the copy constructor is necessary for the case you are describing, therefore, one solution is to make it protected - protecting it from something other than a derived class that uses it and works correctly.
Thanks to the burglar below (as well as night sleep), the solution clearly should make a constructor copy in Circle . Just because you donāt have one for Shape does not mean that you cannot have it in a derived class:
class Circle: public Shape { public: Circle(int i) : a(i) {} Circle(const Circle& other) { a = other.a; }
The reason he is trying to use the Shape constructor is because you don't have one in your class. You should!
You can also do (as Robson explained):
class Circle: public Shape { public: Circle(int i) : a(i) {} Circle* clone() const { return new Circle(a); } int a; };
And generally do not need a copy constructor. Both of these solutions allow "you are trying to use a remote Shape(const Shape &) constructor . This is really obvious as soon as you see it.
Mats petersson
source share