-1

I got following code:

 class myarray 
 {  

    float* rawdata;

    float*   GetRawData () const noexcept { return rawdata; };
    float&   GetRawData () const noexcept { return rawdata; };
    const float&   GetRawData () const noexcept { return rawdata; };


 } 

I get compiler error saying it is not possible to overload the first two member functions. Is it not possible for C++ to distinguish since we in a reference would have a different syntax when invoking the function

ATK
  • 1,296
  • 10
  • 26
  • 1
    Correct, it is not possible. – Eljay Feb 20 '21 at 14:31
  • Any [decent book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), class or tutorial should have mentioned it. – Some programmer dude Feb 20 '21 at 14:34
  • 1
    When writing `myarray x; x.GetRawData();` which function should be called? The compiler could not decide. Thus it is not allowed. – Werner Henze Feb 20 '21 at 14:35
  • *since we in a reference would have a different syntax when invoking the function* That's not really true. They would both be invoked by writing `GetRawData()`. What we do with the return value is not something the compiler takes into consideration when choosing an overload. – super Feb 20 '21 at 14:36

1 Answers1

3

Is it not possible for C++ to distinguish

It is not. Overloading is possible with different parameter lists, and in the case of member functions, ref/const qualifiers. But not by return values. Your overloads have identical parameter lists and ref/const qualifiers, so they cannot overload each other.

since we in a reference would have a different syntax when invoking the function

No, we wouldn't. The invokation is identical in both cases:

this->GetRawData()
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
eerorika
  • 232,697
  • 12
  • 197
  • 326