Why is this method called instead of the other?

84 views Asked by At

I have this particular code sample:

 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 perform

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

the method float& Re() { return _Re; } is being called, instead of

float Re() const { return _Re; } which seems to be well prepared to perform cout by securing the data with const.

1

There are 1 answers

3
rozina On

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

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

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

then float Re() const { return _Re; } would be called.