Search code examples
c++assignment-operator

c++ implicitly convert function arguments via custom assignment operator


I'm working on a project with is part C written and partly C++ written.

I got 2 Enums which basically represent the same, however one is wrapped inside a class and the other one is located at a global namespace due to C compatibility.

//C Code File
typedef enum
{
  C_Enum_first = 0,
  C_Enum_Second,
} C_Enum_T
//(obviously) C++ Code file
class CMyClass
  {
  public:
    enum class CPP_Enum
    {
      first= 0,
      second,
    };

    CPP_Enum& operator= ( const C_Enum_T& rhs);
}

Now I have a function at a global namespace scope with takes the Cpp Enum as an argument

bool FooFunc(const CMyClass::CPP_Enum value);

However due to compatibility issues with C code there are some places where this function will be called with a C Enum value

bool res = FooFunc(C_Enum_Second);

This gives me a no known conversion error. Yes I know i can overload, but for demonstration purposes i only showed 1 enum argument. In reality there are 3 enums with will increase my needed overloads. Why is my assignment operator not called? Do assignment operator not work implicitly on function arguments?

thx for your help

greets Julian :)


Solution

  • Do assignment operator not work implicitly on function arguments?

    Your operator= is a member of CMyClass. It can be called like this:

    CMyClass cmc;
    C_Enum_t a;
    CPP_Enum& x = (cmc = a);
    

    But it will not be considered for implicit conversion from CMyClass to CPP_Enum. Consider to use a free function for the conversion instead. Also it is rather fishy that your operator= returns a reference. You didn't include the implementation, but returning a reference does not look right. What should it refer to?