3

In the following :

template<typename Derived>
class Base:
{
    inline Derived& operator=(const Base<Derived>& x);
}

Does this declaration erases the default copy assignment operator or do I have two operators :

inline Derived& operator=(const Base<Derived>& x); 
// (declared by me)

AND

inline Base<Derived>& operator=(const Base<Derived>& x); 
// (declared by the compiler)

In this case, when I call the function, how the compiler will get the right operator ?

Vincent
  • 57,703
  • 61
  • 205
  • 388

2 Answers2

3

If you declare any method that can pass for an assignment operator:

XXX Foo::operator=(Foo&);
XXX Foo::operator=(Foo const&);
XXX Foo::operator=(Foo volatile&);
XXX Foo::operator=(Foo const volatile&);

then the compiler will not generate the default version Foo& operator=(Foo const&);.

Note that the return type is completely free, as for other methods. You could use void, bool, whatever really. It is just idiomatic (but not required) to return a reference to self in order to allow assignment chaining: a = b = c = 0; which itself stems from the guideline that overloaded operators should follow the semantics of their built-in counterparts.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
1

Have you tried? Overloading by return type only would be a compile error, so my guess is that the one defined replaces the default one.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • It would be a compiler error only if the template was actually instantiated in the code. Otherwise, it will compiler just fine. – SomeWittyUsername Dec 09 '12 at 09:14
  • @icepack that is true, im assuming the template is instantiated – Karthik T Dec 09 '12 at 10:20
  • 1
    @icepack this is not true. if a template is always illformed regardless of what template parameters you pass, then a template can be rejected without instantiation too. this applies to his class template then, if the default assignment operator would be instantiated too. – Johannes Schaub - litb Dec 09 '12 at 12:37
  • @JohannesSchaub-litb Good point. However, this is compiler-specific, isn't it? The fact that the compiler can do this, doesn't mean it will. As far as the generated binary code concerned, it's fine. – SomeWittyUsername Dec 09 '12 at 13:04
  • @icepack right. it's basically no more than undefined behavior then. I.e http://stackoverflow.com/questions/11589766/why-doesnt-this-code-generate-compilation-errors – Johannes Schaub - litb Dec 09 '12 at 13:07
  • @JohannesSchaub-litb : are you ok with the validated answer or do you think that the provided code has an undefined behaviour ? – Vincent Dec 10 '12 at 01:33