2

Why in c++ standard ( I look at cpp reference site) two variants with the same signature are allowed?

For example:

reference front();
const_reference front() const; 
Skotti Bendler
  • 753
  • 1
  • 6
  • 17
  • See [here](https://stackoverflow.com/questions/856542/elegant-solution-to-duplicate-const-and-non-const-getters). These are the non-const and const versions of this function. The trailing `const` in the second function changes the signature from the first one. – Cory Kramer Mar 02 '17 at 13:31
  • relates/dupe: http://stackoverflow.com/questions/27825443/same-function-with-const-and-without-when-and-why – NathanOliver Mar 02 '17 at 13:32

3 Answers3

6

That trailing const is part of the signature. Pretend the implicit this is explicit:

reference       front(      This *this);
const_reference front(const This *this);

Clearly the argument lists are different.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • It's actually `Type&` or `const Type&`. – NathanOliver Mar 02 '17 at 13:31
  • Yes `this` is a pointer but the function parameter takes a reference to the object it is called on. – NathanOliver Mar 02 '17 at 13:33
  • 1
    Well, there is no function parameter, so we could argue all day about how we want to pretend it may look. My mental model is to treat `this` as an argument to the member function I am using it in. So it must be some kind of pointer. – BoBTFish Mar 02 '17 at 13:36
  • @user2079303 You could bind a pointer, reference, or smart pointer. – BoBTFish Mar 02 '17 at 13:37
  • I used to think this way. But it cannot explain member functions with ref-qualifiers in C++11. – cpplearner Mar 02 '17 at 13:37
  • @BoBTFish really? I hadn't even though that might be possible. Never mind the noise then. – eerorika Mar 02 '17 at 13:38
  • I can't find the reference so I could be totally wrong. I can find what `this` is but not the implicit function parameter. Could swear it is a reference but I guess it really doesn't make a difference. – NathanOliver Mar 02 '17 at 13:39
  • In the unified call syntax proposal, the alternative member call syntax seems to use a reference: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0251r0.pdf – eerorika Mar 02 '17 at 13:44
  • Bear in mind `this` existed in the language before references did, and is not specified in any way as an "implicit parameter", just as a magical keyword. – BoBTFish Mar 02 '17 at 13:49
4

two variants with the same signature

That's a common misconception. The const at the end of the signature is part of the signature.

It can be useful, for example, with container classes that return references to the contained data. The const version returns a const reference so the datum cannot be modified through that reference.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

Because the const in the second function counts as part of the signature.

const_reference front() const; 
                     // ^^^^^
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190