0

In my program, I am trying to use the assignment operator= to assign an object of my class. I am specifically trying to call the assignment operator instead of an implicit constructor (thus the explicit keyword). When I try to compile, I get a C2440 Compiler Error:

class MyClass {
public:
    explicit MyClass(double x = 0.) :
        m_x(x) {
    }

    MyClass& operator = (const double& other) {
        m_x = other;

        /* do something special here */

        return *this;
    }
private:
    double m_x;
};

int main()
{
    MyClass my_class = 2.; // C2440

    return 0;
}

I guess that the compiler fails trying to call the constructor implicitly (because of explicit). Does anyone have a fix?

jakob
  • 147
  • 1
  • 7
  • 2
    Would `MyClass my_class; my_class = 2.;` be an acceptable solution? – Ted Lyngmo May 04 '21 at 21:34
  • 1
    `Does anyone have a fix?` Remove `explicit`? What is there to fix - everything working as intended - compiler is failing code that should be failing. How do you want to fix it? – KamilCuk May 04 '21 at 21:36
  • 2
    `MyClass my_class = 2.;` is more or less equivalent to `MyClass my_class(2.);`, but, you said that it in `explicit`, which makes that invalid. – ChrisMM May 04 '21 at 21:36
  • @ChrisMM That is explicit so ... go for that as an answer - even though it doesn't use the assignment operator – Ted Lyngmo May 04 '21 at 21:38
  • There is no operator in `MyClass my_class = 2;` so hiding the constructor will never magically make a call to an assignment operator. According to the C++ grammar, this is a variable definition with a copy initialization. It doesn't become some other grammar production just because your constructor is declared explicit (although C++ has stateful grammar, so things *can* parse differently, this example doesn't) – Ben Voigt May 04 '21 at 21:47

1 Answers1

3

MyClass my_class = 2.; is more or less equivalent to MyClass my_class(2.);, but, you marked the constructor as explicit, which prevents C++ from doing that automatically.

So, in the way you've written your code, you cannot really do what you want. You could explicitly call the constructor using:

MyClass my_class(2.); // Explcitly call your constructor

Or, as Ted Lyngmo mentioned in the comments, you can do:

MyClass my_class; // Call your constructor with default argument of 0
my_class = 2.; // then call your assignment operator
ChrisMM
  • 8,448
  • 13
  • 29
  • 48