Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: passing 'xxx' as 'this' argument discards qualifiers

Tags:

c++

Can anyone tell me why the following code:

#include <iostream>
using namespace std;

class Test {
    int a, b, c;
public:
    Test() : a(1), b(2), c(3) {}
    const void print() {cout << a << b << c;}
    int sum() {return (a+b+c);}
};

const Test& f(const Test& test) {
    test.print();
    // cout << test.sum();
    return test;
}

main() {
    Test x;
    cout << "2: ";
    y = f(x);
    cout << endl;
}

gives the compile error

"error: passing 'const Test' as 'this' argument discards qualifiers"

?

My print() method is const, which is all I'd understood was necessary. For me the (commented out) sum() method in f() should give an error, but not the print() method. If anyone can point out to me where I am misunderstanding - that would be great.

like image 915
Aidenhjj Avatar asked Sep 18 '25 08:09

Aidenhjj


1 Answers

You're calling a non-const method print() on a const object. A const method is such that cannot modify the object it's called on, and this is the only sort of member methods you are allowed to call on const objects (to preserve the const-ness). A const method is denoted by const after the method arguments list:

void Test::print() const {
   cout << a << b << c;
}

And yes, const void is useless at best, just void is all the same.

like image 77
Violet Giraffe Avatar answered Sep 20 '25 21:09

Violet Giraffe