BUG: You receive a "C2676" error message when both unary and binary operators are overloaded for the same operator (814455)



The information in this article applies to:

  • Microsoft Visual C++ .NET (2003)

SYMPTOMS

When both the unary and binary operators for an operator are overloaded for a class, and the binary operator is defined as a non-member operator with the friend specifier in the class scope, you receive the following error message:
error C2676: binary '-' : 'Test' does not define this operator or a conversion to a type acceptable to the predefined operator
The behavior is observed for any operator that can be overloaded both as a unary and binary operator. This includes the minus (-), the plus (+), and the "*" operator.

CAUSE

The compiler picks up the wrong overloaded operator method.

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

WORKAROUND

To resolve the problem, move the definition of the binary non-member operator outside the class scope. The following code specifies the class that is named Test that overloads the "-=" and the unary minus (-) operator as member operators. The binary minus (-) operator is specified as the non-member operator. The definition of the binary minus (-) operator has been moved outside the class scope.
class Test
{
	friend Test operator-(const Test &a, const Test &b);

	Test& operator-=(const Test& m)
	{
		*this = *this - m;
		return *this;
	}

	//The code provided below is only for illustration purpose.
	Test operator-(void) const
	{
		Test dummy;
		return dummy;
	}
};

//Definition of the overloaded operator is moved out of the class scope for Test.
Test operator-(const Test &a, const Test &b)
{
	Test dummy;
	return dummy;
}

MORE INFORMATION

Steps to Reproduce the Behavior


  1. In Notepad, or any other text editor, paste the following code:
    #include <stdio.h>
    #include <tchar.h>
    
    class Test
    {
    	friend Test operator-(const Test &a, const Test &b)
    	{
    		Test dummy;
    		return dummy;
    	}
    
    	Test& operator-=(const Test& m)
    	{
    		*this = *this - m; //C2676 on this line.
    		return *this;
    	}
    
    	Test operator-(void) const
    	{
    		Test dummy;
    		return dummy;
    	}
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	return 0;
    }
    Note Both the unary and binary minus(-) operators are defined in the scope of the class, where the operators are being overloaded.
  2. Save the file as Test.cpp.
  3. Open a .NET command prompt, and then type the following command:
    cl /c Test.cpp
You receive the compiler error message that is described in the "Symptoms" section of this article.

Modification Type:MinorLast Reviewed:1/19/2006
Keywords:kbCompiler kberrmsg kbBug KB814455 kbAudDeveloper kbAudITPRO