Why is this method called instead of another?

I have this example code:

 struct ComplexNumber {
      float  _Re, _Im;
     public:
      float  Re() const { return _Re; }
      float& Re()       { return _Re; }

      float  Im() const { return _Im; }
      float& Im()       { return _Im; }
    };

      

and I would like to know why when I execute

ComplexNumber Num1;
cout << Num1.Re() << endl;

      

the method is called float& Re() { return _Re; }

instead

float Re() const { return _Re; }

which seems to be well prepared for cout execution by providing data with const.

+3


source to share


1 answer


The best matching function is called, so if you have a const and a non const version, the non const version will be called on the non const object.

If you had a const object (or pointer or reference)



const ComplexNumber Num1;
cout << Num1.Re() << endl;

      

then it float Re() const { return _Re; }

will be called.

+3


source







All Articles