Home > Backend Development > C++ > Why Are `getId()` and `getName()` Causing 'Passing 'const' Object as 'this' Argument' Errors in C ?

Why Are `getId()` and `getName()` Causing 'Passing 'const' Object as 'this' Argument' Errors in C ?

DDD
Release: 2024-12-23 20:18:15
Original
802 people have browsed it

Why Are `getId()` and `getName()` Causing

Error: Passing Const Objects as 'this' Arguments

In the given C code, you encounter an error while attempting to access the getId() and getName() member functions of objects stored in a std::set:

<br>error: passing 'const StudentT' as 'this' argument of 'int StudentT::getId()' discards qualifiers<br>error: passing 'const StudentT' as 'this' argument of 'std::string StudentT::getName()' discards qualifiers<br>

This error stems from the fact that the objects within the std::set are stored as const StudentT instances. When you call the getId() and getName() functions on these const objects, the compiler detects a problem.

In C , non-const member functions are not allowed to modify const objects. getId() and getName() are non-const functions that can potentially modify the object they're invoked on. However, since the objects in the set are const, any attempt to modify them through these member functions would be an error.

The solution is to make the getId() and getName() functions const as well:

int getId() const {
    return id;
}

string getName() const {
    return name;
}
Copy after login

By making these functions const, you indicate that they won't modify the object they're invoked on, and the compiler will allow their use on const objects.

Additionally, it's recommended to implement the operator< as a const reference to match its intended use as a comparison function:

inline bool operator< (const StudentT & s1, const StudentT & s2) {
    return s1.getId() < s2.getId();
}
Copy after login

The above is the detailed content of Why Are `getId()` and `getName()` Causing 'Passing 'const' Object as 'this' Argument' Errors in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template