Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does const mean in c++ in different places

Tags:

c++

What is the difference between

    const string& getName() const {return name;}

and

    string& getName() const {return name;}

What does const mean at the beginning and at the end?

like image 762
Laura Avatar asked May 07 '12 12:05

Laura


People also ask

What does const mean in C programming?

Const (constant) in programming is a keyword that defines a variable or pointer as unchangeable. A const may be applied in an object declaration to indicate that the object, unlike a standard variable, does not change. Such fixed values for objects are often termed literals.

Does it matter where you put const?

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.

Why do we use const in C?

We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value of the value of PI, you wouldn't like any part of the program to modify that value.

What does the prefix const mean?

Const is programming syntax that is used to declare a constant variable in languages like C. This is one way of creating a variable that will be used once or many times in code. A constant variable is one that will not change after the program is complied.


2 Answers

The const at the end of the function signature means the method is a const member function, so both your methods are const member functions.

The const at the beginning means whatever is being returned is const.

The first example is a const method returning a const reference to internal data, and is therefore const-correct.

The second is a const method returning non-const reference to internal data. This is not const-correct because it means you would be able to modify the data of a const object.

A call to a const a method cannot change any of the instance's data (with the exception of mutable data members) and can only call other const methods.

Const methods can be called on const or non-const instances, but non-const methods can only be called on non-const instances.

like image 168
juanchopanza Avatar answered Nov 02 '22 23:11

juanchopanza


One returns a const reference and is a const member function , the other is a const member function.

const string& getName() const {return name;}

the returned string can't be modified, and the method is const (see below).

string& getName() const {return name;}

the method can't modify non-mutable class members.

like image 27
Luchian Grigore Avatar answered Nov 03 '22 00:11

Luchian Grigore