There already popped up two good answers while i was writing this, but i submit my anyway because it is written in another style. Maybe this more shallow answer is useful to someone.
First of all, it is a bit unclear with the copy
method being part of an object, taking an object as input, and returning an object. Does it copy from or to the input? Does it return a copy or itself? Is it supposed to be static
?
All of your declarations "work" (depending on what you wish to achieve), but not all of them together.
Edit: I removed the part disputed in the comments, the other answers covers that anyway. But i kept the part giving an example to explain why polymorphism on return type isn't allowed.
To only use implementations in Derived
, you can declare
class Derived:public Base{
public:
virtual Derived* copy(Base* b){...};
virtual Derived* copy(Derived* b){};
};
or
class Derived:public Base{
public:
virtual Base* copy(Base* b){...};
virtual Derived* copy(Derived* b){};
};
Polymorphism based on return type is not supported in C++, however. You cannot use
class Derived:public Base{
public:
virtual Base* copy(Derived* b){...};
virtual Derived* copy(Derived* b){};
};
because the compiler will have trouble determining what to do if you do not use the result. Consider:
Derived * d = new Derived();
Derived * toCopy = new Derived();
Base * b2 = toCopy->copy(d); // Should use use the version returning Base
Derived * d2 = toCopy->copy(d); // Should use the version returning Derived
toCopy->copy(d2); // Which implementation should the compiler pick? It cannot know!
Because the compiler cannot decide on the version to use in the last line above, it is illegal to overload on return type.
As for the access right, i gladly recommend the other answers.