A
aegis
Consider the following:
#include <iostream>
using namespace std;
class X {
public:
X& operator=(const X& o)
{
if(this != &o) {
a = o.a;
}
return *this;
}
X() { a = 10; }
void set(int val) { a = val; }
int get() { return a; }
private:
int a;
};
int main(void)
{
X x;
x.set(100);
X p = x;
cout << p.get() << endl;
return 0;
}
If I change a = o.a in the overloaded assignment method,
then I get the following from g++:
g++ -o t t.cpp
t.cpp: In method `X &X:perator= (const X &)':
t.cpp:10: passing `const X' as `this' argument of `int X::get ()'
discards qualifiers
What this is saying is that because my 'o' is of type:
const X&, then get() method discards the qualifier.
But does it really? In addition, if I modify the prototype
of 'get()' to: int get() const, then I have no problem.
Yet why should this matter as the return type of 'get'
is the object type 'int'?
#include <iostream>
using namespace std;
class X {
public:
X& operator=(const X& o)
{
if(this != &o) {
a = o.a;
}
return *this;
}
X() { a = 10; }
void set(int val) { a = val; }
int get() { return a; }
private:
int a;
};
int main(void)
{
X x;
x.set(100);
X p = x;
cout << p.get() << endl;
return 0;
}
If I change a = o.a in the overloaded assignment method,
then I get the following from g++:
g++ -o t t.cpp
t.cpp: In method `X &X:perator= (const X &)':
t.cpp:10: passing `const X' as `this' argument of `int X::get ()'
discards qualifiers
What this is saying is that because my 'o' is of type:
const X&, then get() method discards the qualifier.
But does it really? In addition, if I modify the prototype
of 'get()' to: int get() const, then I have no problem.
Yet why should this matter as the return type of 'get'
is the object type 'int'?