Const Object and Const Member Function

◀ Private Versus Public Data Members▶ Friend Class and Friend Function
Amazon Assume Student is a class that takes the student’s name as an argument in its constructor and getName() returns a string which is the name of the student. Let’s see how we can promise the compiler that the object will not be modified. Consider the following code snippet:
const Student saint = Student(“Maolin Yeh”);
saint.getName();
The object, saint, is declared to be const, meaning that its data members are not supposed to be altered in any way. However, the member function, getName(), needs to guarantee that it won’t modify the invoking object.


The way to achieve it is to add keyword const after the function parentheses. Here is what the getName() declaration inside Student should look like:
string getName() const;
Similarly, the function definition, if defined outside Student, looks like this:
string Student::getName() const {
	return name;
}

◀ Private Versus Public Data Members▶ Friend Class and Friend Function

fShare
Questions? Let me know!