Reputation: 1289
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.
Upvotes: 4
Views: 6632
Reputation: 33589
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.
Upvotes: 8
Reputation: 36483
const void print()
This makes no sense, you meant:
void print() const
Upvotes: 5