Why Using the Const Keyword Before and After Method or Function Name

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

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'
}

What is meant with const at end of function declaration?

A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.

Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit this pointer. So a method int Foo::Bar(int random_arg) (without the const at the end) results in a function like int Foo_Bar(Foo* this, int random_arg), and a call such as Foo f; f.Bar(4) will internally correspond to something like Foo f; Foo_Bar(&f, 4). Now adding the const at the end (int Foo::Bar(int random_arg) const) can then be understood as a declaration with a const this pointer: int Foo_Bar(const Foo* this, int random_arg). Since the type of this in such case is const, no modifications of member variables are possible.

It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword mutable. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)

As usual when dealing with the const keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of const only applies when adding const to the end of the function declaration after the parenthesis.

const is a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings about const correctness and the const keyword:

Const correctness

The C++ 'const' Declaration: Why & How

What does const after function header do?

From the Const Correctness tutorial:

If you have a const object, you don't want to call methods that can
change the object, so you need a way of letting the compiler know
which methods can be safely called. These methods are called "const
functions", and are the only functions that can be called on a const
object. Note, by the way, that only member methods make sense as const
methods. Remember that in C++, every method of an object receives an
implicit this pointer to the object; const methods effectively receive
a const this pointer.

It might be worthwhile (spoiler: it is) to read through the whole article if you're new to the concept of constness.

Const before or const after?

why is there two correct ways of specifying const data and in what situation would you prefer or need one over the other if any?

Essentially, the reason that the position of const within specifiers prior to an asterisk does not matter is that the C grammar was defined that way by Kernighan and Ritchie.

The reason they defined the grammar in this way was likely that their C compiler parsed input from left-to-right and finished processing each token as it consumed that. Consuming the * token changes the state of the current declaration to a pointer type. Encountering const after * means the const qualifier is applied to a pointer declaration; encountering it prior to the * means the qualifier is applied to the data pointed to.

Because the semantic meaning does not change if the const qualifier appears before or after the type specifiers, it is accepted either way.

A similar sort of case arises when declaring function pointers, where:

  • void * function1(void) declares a function which returns void *,

  • void (* function2)(void) declares a function pointer to a function which returns void.

Again the thing to notice is that the language syntax supports a left-to-right parser.

What does const mean following a function/method signature?

It means that the method do not modify member variables (except for the members declared as mutable), so it can be called on constant instances of the class.

class A
{
public:
int foo() { return 42; }
int bar() const { return 42; }
};

void test(const A& a)
{
// Will fail
a.foo();

// Will work
a.bar();
}

Why use the keyword 'const' twice in a class member function C++

The first const qualifies the returned value as non-modifiable; the second const specifies that the function does not modify the class instance (or any member of it) on which it was called.

The first is more often used when the function returns a reference to a member, to prevent that returned reference from being used to modify the member to which it refers.



Related Topics



Leave a reply



Submit