binding of reference to a value of type drops qualifiers

The error is indicating that you cannot bind a non-const reference to a const-object, as that would drop (discard in other compiler's errors), disregard or ignore the const qualifier.

What it tries to indicate is that if the operation was allowed you would be able to modify the object through the reference ignoring the fact that the object itself is const, breaking const-correctness.

In your particular code, the function __median in the library takes __a, __b, and __c by const reference and tries to call the __comp function, which in your program (first declaration) takes the second argument by non-const reference. To be able to call __comp(__a,__b) (or any other call to __comp in that function) it would have to bind an object accessible only through a const& to the second argument that takes a non-const reference. This is most probably a typo, since you define compare below with both arguments being const references.

Change the declaration of compare before main to:

bool compare(const Student_info&, const Student_info&);
//                                ^^^^^

the error: binding reference of type ‘((type))&’ to ‘const ((type))’ discards qualifiers can also originate from a const member function of a class, like void MyClass::myFunc() const {}

#include <iostream>

// comment next line to make code work
#define BROKEN

class C2 {
public:
    void f(int &i);
};
void C2::f(int &i) { i++; }

class C1 {
public:
    C1();
    int i;
    C2 c2; C2* pc2;
    void f_nonconst();
    void f_const() const;
};
C1::C1() { c2 = C2(); pc2 = &c2; }

void C1::f_nonconst() {
    pc2->f(i);
    // no error
}

#ifdef BROKEN
void C1::f_const() const {
    pc2->f(i);
    // error: binding reference of type ‘int&’ to ‘const int’ discards qualifiers
}
#endif

#define print_i() { std::cout << "i = " << pc1->i << std::endl; }
int main() {
    C1 c1 = C1();
    C1* pc1 = &c1;

    print_i(); pc1->f_nonconst();
#ifdef BROKEN
    print_i(); pc1->f_const();
#endif
    print_i();
}

related to Meaning of 'const' last in a function declaration of a class?

Tags:

C++