"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Passing a Const Object to a Non-Const Member Function Cause a Qualifier Disqualification Error in C++?

Why Does Passing a Const Object to a Non-Const Member Function Cause a Qualifier Disqualification Error in C++?

Published on 2025-01-14
Browse:608

Why Does Passing a Const Object to a Non-Const Member Function Cause a Qualifier Disqualification Error in C  ?

Passing Const Objects as 'this' Argument: Qualifier Disqualification Error

In C , passing const objects as 'this' arguments to member functions can result in "passing 'const xxx' as 'this' argument of member function discards qualifiers" errors. This occurs because the compiler considers the possibility that non-const member functions may modify the object, which is prohibited for const objects.

Problem Analysis

In the provided code, the objects in the set are stored as const StudentT. When accessing member functions getId() and getName() within the loop, the compiler detects this issue since the objects are const and the member functions are not marked as const.

Solution

To resolve the error, the getId() and getName() functions must be made const:

int getId() const {
    return id;
}

string getName() const {
    return name;
}

This allows the functions to be called on const objects without violating the const rules.

Additional Notes

  • Similarly, the operator
inline bool operator
  • Passing references (instead of objects) to member functions is preferable for performance and code correctness.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3