Search code examples
c++assignment-operatormember-hiding

C++ assignment operator resolving


Consider the following code:

struct A
{
    void foo( const char * ) { cout << __PRETTY_FUNCTION__ << endl; }
    A & operator = ( const A &  ) { cout << __PRETTY_FUNCTION__ << endl; return * this; }
};


struct B : public A
{
    void foo( const char * ) { cout << __PRETTY_FUNCTION__ << endl; }
    A & operator = ( const A & other ) { cout << __PRETTY_FUNCTION__ << endl; return * this; }
};

Then when we call this members:

B b;

b.foo( "hehe" );
b = b;

Will be printed:

void B::foo( const char *)
A& A::operator=(const A&)

Question: why B::foo hides A::foo, but B::operator= doesn't?


Solution

  • What you see is not a hiding problem at all. 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, if your question "Question: why B::foo hides A::foo, but B::operator= doesn't?" should be read "How is operator= different from an ordinary function", the difference is compiler will provide one for you if you do not write your own.