Reputation: 4099
In the below code, I could not understand why class A's overloaded assignment operator is being called for class B's assignment since these classes are not related (inheritance)?
class A {
public:
void operator=(const A& rhs) {
if (this == &rhs) cout << "self-assigned";
}
};
class B {
A a; // should not be a pointer member, (i.e) A* a
};
int main() {
B b;
b = b; // Ans: self-assigned
}
Also, if there is any custom assignment operator implemented in class B then it will be invoked taking precedence over class A's.
Upvotes: 1
Views: 119
Reputation: 43662
It's being called for the a member variable you declared. You're doing a copy of the object (into the same object) and thus every member variable is being copied by the default assignment operator.
This operator (compiler-generated) copies each member (recursively). It works by invoking the copy constructor on each field in the instance with the corresponding field in the object the copy is being created from.
Also take a look at http://en.cppreference.com/w/cpp/language/as_operator
Upvotes: 2
Reputation: 70929
If you have not provided an assignment operator the compiler auto-generates one that performs assignment on each of the class's members. In this auto-generated assignment operator, your overload of the assignment operator of A
will be called.
Upvotes: 2