Reputation: 505
I would like to be able to copy either a derived or a base object to a derived object, and I would like the correct operator to be chosen polymorphically depending on the type of the copied object.
This code does not work, I would like b1 = (A&)b2;
to use B & operator= (B const &other)
because b2
is a B
, but it uses B & operator= (A const &other)
:
#include<iostream>
using namespace std;
class A {
public:
A & operator= (A const &other) {
// Here copy A members...
cout<<"A to A"<<endl;
return *this;
}
};
class B: public A {
public:
B & operator= (A const &other) {
A::operator=(other); // Copy A members.
cout<<"A to B"<<endl;
return *this;
}
B & operator= (B const &other) {
A::operator=(other); // Copy A members.
// Here copy B members...
cout<<"B to B"<<endl;
return *this;
}
};
int main()
{
B b1, b2;
A a2;
b1 = b2;
cout<<endl;
b1 = (A&)b2;
cout<<endl;
b1 = a2;
cout<<endl;
return 0;
}
I guess I have to make something virtual
but I don't find how.
Upvotes: 1
Views: 513
Reputation: 206717
I would like to be able to copy either a derived or a base object to a derived object, That is a symptom of poor design.
It's better to strive for a design where the only the leaf-level classes in a class hierarchy are instantiable. This allows you to have clean, non-virtual
, assignment operator functions deal only with objects of right type.
class A {
public:
// Make A uninstantiable.
virtual ~A() = 0;
A & operator= (A const &other) {
// Here copy A members...
cout<<"A to A"<<endl;
return *this;
}
};
class B: public A {
public:
// Not necessary.
// B & operator= (A const &other) { ... }
B & operator= (B const &other) {
A::operator=(other); // Copy A members.
// Here copy B members...
cout<<"B to B"<<endl;
return *this;
}
};
Upvotes: 2