I am using the STL function
sort
from the
algorithm header file but I am having some issues with the
binary predicate parameter that the function uses. Consider the skeletal illustrations below:
1 2 3 4 5 6 7 8 9 10 11 12
|
int main()
{
vector<extPersonType> addressBook;
.
.
.
sort(addressBook.begin(), addressBook.end(), myComp);
.
.
return 0;
}
|
Here is how I defined the binary predicate,
myComp
:
1 2 3 4 5 6 7 8
|
bool myComp (const extPersonType& p, const extPersonType& q)
{
string u, v, w, x;
p.getName(u, v);
q.getName(w, x);
return(v < x);
}
|
Class
extPersonType is derived from class
personType as briefly outlined below:
1 2 3 4 5 6 7 8 9 10
|
class extPersonType: public personType
{
int phoneNo;
public:
extPersonType(fName = "", lName = "", phNo = 0);
void getName(string&, string&);
.
.
.
};
|
1 2 3 4 5 6 7 8 9 10 11
|
class personType
{
string firstName;
string lastName;
public:
personType(fName = "", lName = "");
void getName(string&, string&);
.
.
.
};
|
The program would not compile! I got these error messages for
lines 5 & 6
of the
myComp
binary predicate (function) definition:
passing `const extPersonType' as `this' argument of `void extPersonType::getName(std::string&, std::string&)' discards qualifiers
|
passing `const extPersonType' as `this' argument of `void extPersonType::getName(std::string&, std::string&)' discards qualifiers |
Here are my questions:
Qn 1: I know that making the
getName
functions in classes
extPersonType
and
personType
const would rectify the problem. However, can someone please break down what these error messages mean? How does 'this' argument come into play here? And what are the qualifiers being referred to?
Qn 2: Trying to circumvent the problem above, I removed the
const and used ordinary reference parameters for
myComp
as shown below:
1 2 3 4 5 6 7 8
|
bool myComp (extPersonType& p, extPersonType& q)
{
string u, v, w, x;
p.getName(u, v);
q.getName(w, x);
return(v < x);
}
|
and then I got the error message below referencing
line 7
in function
main:
invalid initialization of reference of type 'extPersonType&' from expression of type 'const extPersonType' |
What does this mean?
Note: Passing the parameters by value into the
myComp
function works perfectly! I know it's not the best approach for the simple reason that the passed objects may be huge in size.