cpp mark getter as const
To mark a getter function as const
in C++, follow these steps:
- Declare the getter function: Begin by declaring the getter function in the class definition. The function should return the desired data type and have no parameters. For example, if you want to create a getter function for a member variable called
mark
, you would declare it like this:
int getMark() const;
- Define the getter function: Define the getter function outside the class definition. In the function definition, use the
const
keyword after the function name to indicate that the function will not modify the object's state. For example:
int ClassName::getMark() const {
return mark;
}
- Add the const specifier: After the closing parenthesis of the function declaration, add the
const
specifier. This specifier indicates that the member function does not modify the state of the object. For example:
int getMark() const;
By adding the const
specifier, you are ensuring that the getter function can be called on constant objects and does not modify the object's state.