Question

I have some confusion about the calling of the overloaded operator().

There are two functions in class matrix:

float operator()(int, int) const; // suppose I call this function rvalue
float& operator()(int, int); // and lvalue

now when I call them in main, in this way :

Matrix M2(3, 2);
M2(0, 0) = 1; // here lvalue should be called
int c=M2(0,0); // and here rvalue

but in both cases it calls lvalue function. why??

if I comment lvalue function and I do

int c=M2(0,0); // now it calls rvalue function

but in presence of both functions, it calls lvalue function. why?

Hope, my question is clear.

Was it helpful?

Solution

Rvalues of class types are not const as you might think. The const overload will be called on const qualified objects, but otherwise the least qualified version is preffered.

What you can do is overload with ref-qualifiers (C++11 only):

float operator()(int, int) && const; // called when object is rvalue 
float& operator()(int, int) &;       // called when object is lvalue
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top