Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: different behaviour of overloading function and operator

Tags:

c++

I'm new to and learning C++. I have a question for function overload for classes.

I have two exactly same code below except the function name. One is just a function and the other is operator.

#include <iostream>

using std::cout;
using std::endl;

class B;

class A {
  public:
    void test(A const &a) { cout << "AA" << endl; }
    void test(B const &b) { cout << "AB" << endl; }
};

class B : public A {
  public:
    void test(A const &a) { cout << "BA" << endl; }
};

int main() {
  B b1;
  B b2;
  b1.test(b2);
  return 0;
}

This program prints

BA

And here is another program.

#include <iostream>

using std::cout;
using std::endl;

class B;

class A {
  public:
    void operator=(A const &a) { cout << "AA" << endl; }
    void operator=(B const &b) { cout << "AB" << endl; }
};

class B : public A {
  public:
    void operator=(A const &a) { cout << "BA" << endl; }
};

int main() {
  B b1;
  B b2;
  b1.operator=(b2);
  return 0;
}

This program prints

AA

The only difference between these two programs is function name: test and operator=. I don't understand why C++ behaves like this. Is there anything I'm missing?

I'm compling this program with g++ version of 4.2.1 under mac OS X 8.2

Thanks!

like image 489
lbyeoksan Avatar asked Aug 14 '26 04:08

lbyeoksan


1 Answers

In your first case, it is not about overloading, those two test functions in A are overloading, however, test in B and A is name hiding since B redefines test. overloading deals with function in same scope with name hiding is talking about class hierarchy.

So in the first case

b1.test(b2);

b2 is an object of B, the test function in B expects const reference of class A, which is OK in this case, so it will output "BA".

In the second assignment operator case, you did not create an assignment operator to assign B into B, therefore the compiler created one for you. The one created by the compiler is calling assignment operator of A. Therefore, AA is printed.

If you add another operator= in B:

void operator=(B const &B) { cout << "BB" << endl; }

You will see "BB" printed out in your assignment operator case since in this case, compiler will not generate assignment operator for you.

like image 129
taocp Avatar answered Aug 15 '26 18:08

taocp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!