Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overloading a function by return type?

One of the most viewed questions here on SO is the question that deals with overloading of various operators. There is something I don’t understand about the overloading of brackets operator operator[]. My question is about the following code:

class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
  // ...
};

Here the operator is overloaded twice, one function which allows the change of members and one which does not. I read that c++ doesn’t allow function overloading by return type, but this looks like it. T& is changed to const T&. Can someone explain to me what exactly is this "overloading" called and why does this work?

Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PS: If this works because the second const keyword changes the "invisible" this pointer argument to const this then I understand, but still, is there a name for that practice?

>Solution :

For overloading to work the functions need to have different signatures (the return type does not count).

In methods the this pointer to the object also counts as an implicit (first) argument. Static methods of course don’t have a this pointer, so they can be treated like global functions.

In your example the two methods have different arguments. idx is identical in both cases but the first method has a this pointer of type X*, which is a variable pointer. In the second method the this pointer is a constant type: const X* and is thus distinct from the first one, that’s why the overloading works.

The return value is inconsequential to the overloading. If only the return values were different, overloading would not have been allowed by the compiler.

class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
                     // -----------------------^^^^^
                     // This is what makes the overloading possible.
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading