Question about how MQL5 language deals with temporary variables

 

Hello,

I have a question that maybe regards the way MQL5 language deals with temporary variables. I created the following class:

class Dummy
{
  double a;
  
 public:
  Dummy(double _a): a(_a) { }

  Dummy(const Dummy &_v): a(_v.a) { }

  Dummy operator+(double _v) const { return Dummy(a + _v); }

  //Dummy operator+(double _v) const { Dummy tmp(a + _v); return tmp; }
};

If I try to compile, I get the following error:

'Dummy' - no one of the overloads can be applied to the function call
  could be one of 2 function(s)
    Dummy::Dummy(double)
    Dummy::Dummy(const Dummy&)

Instead, if I use the other implementation (that is commented out in the previous code) and explictly instantiate a temporary variable, everything works fine:

Dummy operator+(double _v) const { Dummy tmp(a + _v); return tmp; }

Why? I expected that using Dummy(a + _v) was equivalent to creating a temporary double variable equal to a + _v and then calling the Dummy() constructor on that variable.

What is the difference between the two implementations of the operator+() function, and why one woks and the other one does not work?

Thanks

 
Why? Because the compiler can't handle an anonymous temporary variable.
 

Thank you for your answer but I do not understand. This code compiles perfectly, and is identical to the previous implementation (with an anonymous temporary variable created) except for the const keyword that is now missing:

  Dummy operator+(double _v) { return Dummy(a + _v); }

Also this works perfectly (function defined outside the Dummy class but with exactly the same implementation as the operator+() function):

Dummy Sum(double a, double b)
{
  return Dummy(a + b);
}

The only difference here is that the 'a' variable is not a class member.

So, it seems that the problem is not (only at least) related to the handling of anonymous temporary variables but also to something else...

 
Because you cannot distinguish if your "this" is a const object, that's why the compiler cannot apply the const function to your "maybe" const object.

As far as I understand, at least.


Reason: