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?
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?
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.
We use const
in the prefix of the function to ensure whatever is getting returned from the function becomes constant.
And we use const
as the postfix in the function declaration to ensure that the function does not do any modification in the current instance of class i.e if the member function of the class tries to modify the current object's attribute's value then the compiler will throw an error.
const function is mainly used for const object to ensure that the function is not trying to modify current object data.
const string& getName() const {return name;}
return const reference means that you will not be able the instance after returning the reference to it.
string& getName() const {return name;}
const method means that this method will not change the state of the object except the mutable member variables. Also this method can be called on an const object for example:
class MyClass(){
public:
void doSomethingElse()const;
void notConstMethod();
};
void doSomething( const MyClass& obj ){
obj.doSomethingElse();
obj.notConstMethod(); //Error
}