In C++, I see this code.
public:
Ports& GetPorts();
const Ports& GetPorts() const;
Why is it necessary to have another method with const?
How can a compiler decide which method is called?
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.
If you call
x.GetPorts()andxis a non-constobject, the first version will be called. Ifxis aconstobject, on the other hand, the second version will be called. That kind of code is saying “if the object is modifiable, allow the result ofGetPorts()to be modified; if the object isconst, don’t allow the result to be modified.” The compiler will prefer the first version if it matches; however, it will not be present if the object isconstand so the second version will be used instead.