Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual assignment operator

Tags:

c++

Given the code below, shouldn't Calling B be printed, not Calling A? Isn't the runtime type of a a B and hence the virtual call should result in a call to B::operator= (as virtual calls are determined by the left operand)?

#include <iostream>

class A
{
public:
  virtual A& operator=(const A& a_) { std::cout << "Calling A" << std::endl; }
};

class B : public A
{
public:
  virtual B& operator=(const B& b_) { std::cout << "Calling B" << std::endl; }
};

int main() {
  B b1;
  B b2;
  A& a = b1;
  a = b2; // Prints "Calling A", should be "Calling B"?

  return 0;
}
like image 624
Clinton Avatar asked Dec 12 '25 23:12

Clinton


2 Answers

a = b2; is not a virtual call.

The reason for this is that B::operator=(const B&) does not override A::operator=(const A&), because their signatures are different.

You can use override to make the compiler automatically check these things for you.

Using override does two things:

  • prevents simple errors like this (compiler is your best friend)
  • makes the code easier to understand ("oh so this function overrides something")
like image 183
emlai Avatar answered Dec 15 '25 13:12

emlai


The virtual method you have in B (B::operator=(const B&)) doesn't override the one in A (A::operator=(const A&)). I am guessing what you've written is an overload, therefore, compiler can't know such a method exists since you are using an A reference.

like image 31
Fatih BAKIR Avatar answered Dec 15 '25 13:12

Fatih BAKIR