Reputation: 23
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
#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?
Upvotes: 2
Views: 337
Reputation: 12669
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:
B
.Upvotes: 1
Reputation: 1081
I don't see any conflict in this code with standard. b1 = a1; This assignment is done because you used using-declaration of base class. and also " implicit assignment operator of the derived class" is provided by compiler because if you want to assign two objects of derived class it's possible.
Upvotes: 0
Reputation: 546
I think the reference you mentioned should be broken into 2 parts that suite your 2 question:
Upvotes: 0
Reputation: 7100
You can't hide the copy assignment operator of B
because both operators you've mentioned take different parameters.
Upvotes: 1