I have a question about operator=
that accepts parent reference type.
When there is a abstract class and it's implemented class,
why is not enough to have single operator=
that accept parent reference type?
Below is my code
#include <iostream>
class AbstractType {
public:
virtual ~AbstractType() {}
virtual AbstractType& operator=(const AbstractType& other) {
std::cout << "AbstractType& operator=(const AbstractType&)" << std::endl;
return *this;
}
};
class Type1: public AbstractType {
public:
virtual ~Type1() {}
virtual Type1& operator=(const AbstractType& other) {
std::cout << "Type1& operator=(const AbstractType&)" <<
std::endl;
return *this;
}
/*
virtual Type1& operator=(const Type1& other) {
std::cout << "Type1& operator=(const Type1&)" << std::endl;
// Just redirecting here! What a waste!
return operator=(dynamic_cast<const AbstractType&>(other));
}
*/
};
int main()
{
Type1 t1;
AbstractType& r1 = t1;
Type1 t2;
AbstractType& r2 = t2;
// Type1& operator=(const AbstractType&). It's fine!
r1 = r2;
// AbstractType& operator=(const AbstractType&)!! Why??
// Expected `Type1& operator=(const AbstractType&)` to be called!
t1 = t2;
return 0;
}
You can find given parameter is being just redirected in Type1& operator=(const Type1&)
that is ignored by comment.
Uncomment Type1& operator=(const Type1&)
is just working for me,
but if say, I have more than a hundred of TypeX then I have to make two hundred of copy assignment which is I can't understand because it seems to me just having Type1& operator=(const AbstractType& other)
is enough.
And most cases I only have AbstractType to handle things around. Very rare to know it's specific type in advance under limited situations.
Anyone can suggest me better solution?