jlanisdev
jlanisdev

Reputation: 65

Strange behavior when overriding assignment operator on template class

Below is an example of a template class which overloads the assignment operator. Given this class:

template<class Type>
class Attribute
{
public:

    Type operator=( const Type rhs )
    {
        mData = rhs;
        return mData;
    }

private:

    Type mData;
};

Why would this code below compile without any errors?

Attribute<std::string> str;
str = 0;

While seemingly contradictory, this code:

std::string test;
test = 0;

Produces the following error?

error C2593: 'operator =' is ambiguous  

Upvotes: 1

Views: 214

Answers (2)

legends2k
legends2k

Reputation: 32974

std::string has two assignment operators

basic_string& operator=( const CharT* s );
basic_string& operator=( CharT ch )

and 0 can match both the former and the latter. How? 0 is a valid char, the null char, also it's valid to denote the pointer NULL value. Hence the compiler throws the error C2593: 'operator =' is ambiguous.

As for why is accepts it in your Attribute class case, the compiler is able to construct a std::string using this constructor

basic_string( const CharT* s, const Allocator& alloc = Allocator() );

and passes it on as the rhs in your function Type operator=( const Type rhs ); this behaviour is because of implicit conversion the compiler does.

Upvotes: 1

billz
billz

Reputation: 45450

std::string has overloaded operator=, you code compiles fine but has undefined behavior when executing the string constructor because it doesn't accept NULL(thanks Potatoswatter)

basic_string& operator=( const CharT* s );

Note: str = 0; is equal to

std::string str = std::string(NULL);

std::string test;
test = 0;

Here, compiler can't deduct 0 is char type or pointer so it's ambiguous with below two operator overloads:

basic_string& operator=( const CharT* s );
basic_string& operator=( CharT ch );

manually cast 0 to char or char* should make your code compile but you should avoid doing that.

Upvotes: 2

Related Questions