Home > Mobile >  type const ref function const?
type const ref function const?

Time:10-29

So I'm a bit confused by the 2 appearances of const here, what does this mean? Could someone break it down for me? I know what the two statements in the body do, at least I think I do. Can this format be applied to other objects?

...
T const & GetAt(size_t const index) const
{
    if (index < Size) return data[index];
    throw std::out_of_range("index out of range");
}
...

Thanks in advacne to anyone willing to shine some light for me on this.

CodePudding user response:

const in T const & means that this method returns constant reference to T. const in parameter means that index parameter is constant. const after parameter list means that method may be called on constant object or constant reference/pointer to object i.e.:

const YourClass obj;

YourClass const & cref = obj.

obj.GetAt(10);// no compile error.

cref.GetAt(10);// no compile error either.

If method is not constant then calling it on constant object/reference/pointer will lead to compile error.

For other usage of const read this article https://en.cppreference.com/book/intro/const

CodePudding user response:

T const & -> returns a const reference of type T, means a reference that you can access from outside of this function, but const means you cannot modify it.

(size_t const index) -> the parameter index is const and cannot be modified from within the function

GetAt(size_t const index) const -> the method GetAt cannot modify any members in the class and it cannot call non-const-qualified method. You can say that it does not modify the state of the class.

  • Related