Should "get" method be const?


Should "get" methods in a const class be declared with the const keyword as well?
closed account (48T7M4Gy)
Yes.
const ensures the member data referred to is read-only:

1
2
3
4
string getFirstName() const                                
 {                                                           
    return firstName;
}
http://www.learncpp.com/cpp-tutorial/810-const-class-objects-and-member-functions/


Hi the way I look at it is : It's the object which is const, not the class. If the object is const, then it's const variables must be initialised, and any functions violating the constness of the object result in a compile error.

But what if the object is not const? I would suggest it's still a good idea to mark any function not altering the state of the object as const, unless you have anything which might be mutable

Good Luck !!
Topic archived. No new replies allowed.