Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

() operator overloading c++

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.

like image 974
Bramsh Avatar asked Apr 02 '26 06:04

Bramsh


1 Answers

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
like image 138
jrok Avatar answered Apr 03 '26 19:04

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!