error C2662 const parameter

I have a class with 2 fuctions:

1
2
3
4
5
6
7
8
9
10
COLOR_ENUM Flower::GetColor(void)
{
    return m_Color;
}

Flower &Flower::operator =(const Flower &f)
{
    m_Color = f.GetColor();
    return *this;
}


The complier tell me error C2662: 'Flower::GetColor' : cannot convert 'this' pointer from 'const Flower' to 'Flower &'
I search about error C2662, find that change the function GetColor with end of const:
1
2
3
4
COLOR_ENUM Flower::GetColor(void) const
{
    return m_Color;
}

Then is complier stop telling me error.

the question is why error C2662 is about convert 'this' ? I dont try convert 'this'; And funciton 'GetColor()' I must need 'const' even if I not change the class value?
I dont try convert 'this'
Yes, you do. Non-const member functions can only take non-const this parameters. The compiler is not smart enough to look at your function and tell whether or not you're modifying the object. It needs the const there so that it can be sure that the object will not change.
Consider that if you had a const int, you couldn't pass it to a function void (int &), because it requires that the parameter be non-const. This is exactly what's going on here.
Last edited on
Mmm....I don't understand this:
Non-const member functions can only take non-const this parameters.

Can you point out 'Non-const member functions' and 'non-const this parameters' in this funciton? Thank you~
Non-const member function:
COLOR_ENUM Flower::GetColor(void);
Const member function:
COLOR_ENUM Flower::GetColor(void) const;
But why 'this' is const? If it's const, when it become const?
It can be const when it does not modify any of its members.

1
2
3
4
5
6
class A {
    int i;
public:
    int f1() const { return i; } // legal because 'i' is not modified
    void f2() const { ++i; } // error because it modifies 'i'
};
'Flower::GetColor' : cannot convert 'this' pointer from 'const Flower' to 'Flower &'


Ok, I know, in the error information 'this' is 'f' in m_Color = f.GetColor(); rather than 'this' in return *this;

I think I mistake 'this'.

Thanks
Topic archived. No new replies allowed.