user192847918275195
user192847918275195

Reputation: 21

Why is base class' assignment operator called?

In the following code I understand that the assignment operator in the struct d is not called on derived1 = derived2; and instead the default assignment operator is generated and called. However I am confused as to why:

Why is not the explicit d assignment operator called on derived1 = derived2; when the upcasting is implicit in b & base2 = derived1?
My guess is that the default operator= (with header void operator=(const derived& d)) is always generated unless explicitly overloaded with the exact same header and will always match with an assignment made of two variables of that same type. Am I on the right path?

struct b {
   int x;
   void operator=(const b& base) {
      std::cout << "base" << std::endl;
   }
}

struct d: b {
   int y;
   void operator=(const b& base) {
      std::cout << "derived" << std::endl;
   }
}

int main() {
   b base1;
   d derived1;
   d derived2;
   b & base2 = derived1;

   derived1 = base1; // output: "derived"
   derived1 = derived2; // output "base"
}

Upvotes: 2

Views: 60

Answers (1)

cigien
cigien

Reputation: 60268

Your guess is mostly correct. The compiler will synthesize a definition of

void operator=(const d&)

for the derived class d. (Unless it's not synthesized because it is explicitly deleted, or certain special member functions are user-defined).

This default operator= has the behaviour that it will do a memberwise copy of the argument, and also call the operator= of its base classes. In this case, that operator prints "base", and that's what you see as output.

Upvotes: 2

Related Questions