I was halfway through working on this piece of code and thought this is obviously not going to compile before hitting the build button. I was surprised that it not only compiled, but linked and worked as well.
If I were to guess I would say that SFINAE is responsible for it compiling… is it?
struct BaseClass
{
public:
BaseClass() {}
template<typename T>
BaseClass(const T& a_other)
{
int i = 0; // for break point
}
template<typename T>
BaseClass& operator= (const T& a_other)
{
int i = 0; // for break point
return *this;
}
private:
BaseClass(const BaseClass& a_other); // Does not have a definition
BaseClass& operator= (const BaseClass& a_other); // Does not have a definition
};
struct MyClass : public BaseClass
{
};
int main()
{
MyClass i, j;
i = j;
return 0;
}
EDIT: I am using Visual-C++ 2008, maybe it is an odd quirk of VS
The code is not legal.
i = jcalls the implicitly defined copy assignment operator inMyClass. This function calls the copy assignment operator for each of its sub-objects, including direct base classes [class.copy 12.8 p28].If you add code to the copy assignment operator for BaseClass you can see where VS is going wrong:
For me this prints out “struct MyClass”. VS is calling the
BaseClasscopy assignment operator by passing the parameter received inMyClass:operator=directly, rather than just theBaseClasssub object of j.SFINAE doesn’t come into play because the template functions aren’t failing. VS is simply generating the implicit copy assignment operator incorrectly.
To sum up:
VS is generating the implicit copy assignment operator as
When it should be: