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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With