Search code examples
c++c++11copy-assignment

Using copy assignment in derived class


The cppreference says:

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

From my understanding, the following code should not compile. Because

  1. B::operator=(const B&) is implicitly declared.
  2. both A::operator=(const A&) and using-declaration are hidden.
#include <iostream>
using namespace std;

class A { 
 public:
    A& operator=(const A& A) {
        cout << "A::opreator=" << endl;
    }   
};

class B : A { 
 public:
    using A::operator=;
};

int main() {
    A a1; 
    B b1; 
    b1 = a1; 
}

However, it compiles successfully and prints "A::operator=", why?


Solution

  • From C++11 Standards#12.8 [emphasis added]:

    24 Because a copy/move assignment operator is implicitly declared for a class if not declared by the user, a base class copy/move assignment operator is always hidden by the corresponding assignment operator of a derived class (13.5.3). A using-declaration(7.3.3) that brings in from a base class an assignment operator with a parameter type that could be that of a copy/move assignment operator for the derived class is not considered an explicit declaration of such an operator and does not suppress the implicit declaration of the derived class operator; the operator introduced by the using-declaration is hidden by the implicitly-declared operator in the derived class.

    The implicit declaration of class B assignment operation will be like this:

    B& B::operator=(const B&)
    

    The parameter type of using-declaration assignment operator in class B is different from implicitly declared assignment operator. Hence, it suppress the implicit declaration of the derived class B operator.

    For understanding on 1 & 2 w.r.t. to the code you have posted:

    1. No, the implicit declaration of assignment operator is suppressed in class B.
    2. No, they will not be hidden.