Are all of the below declarations the same? If so, what is the standard way to declare a constant function?
const SparseMatrix transpose();
SparseMatrix transpose() const;
const SparseMatrix transpose() const;
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The const on the left of the function name means the object that is returned cannot be modified. The const on the right means the method is apart of a class and does not modify any of its data members. Unless or course any of its data members are declared with the
mutablekeyword, in which case modification thereof is permitted despite aconstguard.The placement of the
constkeyword is unimportant when the return type of the function is of non-pointer type:However, note that the placement of the
constkeyword matters when using a pointer as the return type. For example:This method returns a pointer to a const
T. That is, what it points to is immutable. So you cannot do an assignment through a dereference of the returned pointer:When const is placed on the immediate right of the return type (that is a pointer), it means the pointer is const and cannot be changed.
Furthermore, if we have
conston both sides of a pointer return type, and haveconstdenoting “no modification of class members”, then it’s read as the following: