I have come across a situation that conflicts with my current understanding of methods in C++.
I am working through Ivor Horton’s “Beginning Visual C++ 2010” (Wrox Press). On page 449, Example 8_03, a method is defined as:
double Volume() const {
return m_Length * m_Width * m_Height;
}
I had rearranged the modifiers as:
double **const** Volume() {
return m_Length * m_Width * m_Height;
}
From my C# and Java background, I had expected the position of const to be irrelevant, but on compilation I received the error:
error C2662: 'CBox::Volume' : cannot convert 'this' pointer from
'const CBox' to 'CBox &'
The error disappears when I return the order to the way Ivor has it.
Does the order in fact make a difference and this not some exotic bug ? If order does matter, how does one remember the correct positions ?
Thanks,
Scott
When
constis placed after the name of a member method, that is stating that thethispointer is what is constant. That is to say, the original declaration states that the methodCBox::Volume()does not change theCBoxobject on which it is called.The most likely source of error is that the
CBox::Volume()function is being called on aconst CBox, or inside anotherconstmethod of thatCBox.