Why using the const keyword before and after method or function name?

c++
57,139

Solution 1

const T& get_data() const { return data_; }
^^^^^

means it will return a const reference to T (here data_)

Class c;
T& t = c.get_data()             // Not allowed.
const T& tc = c.get_data()      // OK.


const T& get_data() const { return data_; }
                    ^^^^^

means the method will not modify any member variables of the class (unless the member is mutable).

void Class::get_data() const {
   this->data_ = ...;  // is not allowed here since get_data() is const (unless 'data_' is mutable)
   this->anything = ... // Not allowed unless the thing is 'mutable'
}

Solution 2

The const (and volatile) qualifier binds to the left. This means that any time you see const, it is being applied to the token to the left of it. There is one exception, however; if there's nothing to the left of the const, it binds to the right, instead. It's important to remember these rules.

In your example, the first const has nothing to the left of it, so it's binding to the right, which is T. This means that the return type is a reference to a const T.

The second const does have something to the left of it; the function data(). This means that the const will bind to the function, making it a const function.

In the end, we have a const function returning a reference to a const T.

Solution 3

The first const means the function is returning a const T reference.

The second one says that the method is not changing the state of the object. I.e. the method does not change any member variables.

Solution 4

const T& data() const { return data_; }

const after member function indicates that data is a constant member function and in this member function no data members are modified.

const return type indicates returning a constant ref to T

Share:
57,139
Waleed Mohsin
Author by

Waleed Mohsin

Updated on July 05, 2022

Comments

  • Waleed Mohsin
    Waleed Mohsin about 2 years

    I have the following code in my application. Why do we use the const keyword with the return type and after the method name?

    const T& data() const { return data_; }
    
  • mwerschy
    mwerschy about 11 years
    unless they've been defined as mutable ;)
  • stardust
    stardust about 11 years
    @mwerschy Correct. Edited.
  • TSG
    TSG over 10 years
    Looking for more of an explanation in the case of const before the function name...how can a function return a constant ref to T? Does that mean the function returns the same value every time? (eg: the address of a static variable)
  • Constructor
    Constructor about 10 years
    Sorry for such late comment but a function member declared with const could modify all members of the class (even non-mutable ones) via const_casting of a this pointer.