Search code examples
c++operator-keywordeffective-c++

calling of operator = from within derived class


This is from the item 16 of effective C++ 2nd edition scott meyers (page 70)

Author writes without much explanation that when base class operator = is called in the following fashion

Base::operator=(rhs);

some compiler (though incorrectly) reject this, if the operator = was generated by compiler(see item 45) so better use

static_cast<base&>(*this) = rhs;

in item 45 he mentions that if base class operator = is private, derived class = has no right to call it.

but in original question compiler was rejecting it because it was generated by compiler (which has to be public)

any help (link) on this would be helpful. (its very difficult to google these types of questions)


Solution

  • but in original question compiler was rejecting it because it was generated by compiler (which has to be public)

    Maybe I understand what you want.

    Compiler generated assignment operator becomes public. But item 16 isn't about access level. This static_cast<base&>(*this) is a workaround for broken compilers. In item 16 Scott Meyers says that the workaround might be needed when the base class assignment operator is generated by the compiler. Btw, a lot changed since the 2nd edition was out. 3rd edition doesn't mention the workaround any more.

    Regarding private assignment operators. Item 45 says that if base class assignment operator was made private, then the compiler can't generate assignment operator for the derived class, because compiler generated assignment operator relies on base class assignment operator. In that case you would have to manually write the assignment operator for the derived class or leave the derived class without an assignment operator.