I have encountered the following problem which proved to me that I know far too little about the workings of C++.
I use a base class with pure virtual functions
class Base
...
and a derived classes of type
class Derived : public Base{
private:
Foo* f1;
...
Both have assignment operators implemented. Among other things, the assignment operator for Derived copies the data in f1. In my code, I create two new instances of class Derived
Base* d1 = new Derived();
Base* d2 = new Derived();
If I now call the assignment operator
*d1 = *d2;
the assignment operator of Derived is not called, and the data in f1 is not copied! It only works if I do
*dynamic_cast<Derived*>(d1) = *dynamic_cast<Derived*>(d2);
Can someone explain why the assignment operators are not overloaded?
Thanks!
It’s hard to say without seeing the relevant code. Here’s an example that works:
This will print
Bwhen run.Things that you might be doing wrong:
operator=virtual in the base class.operator=as signature that’s more restrictive than that of the parent’soperator=, so you’re not actually overriding the parent’s definition. For example if you changeB& operator=(A& a) { cout << "B" << endl; }toB& operator=(B& a) { cout << "B" << endl; }in the example above, it will no longer printB.