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 const
is placed after the name of a member method, that is stating that the this
pointer is what is constant. That is to say, the original declaration states that the method CBox::Volume()
does not change the CBox
object on which it is called.
The most likely source of error is that the CBox::Volume()
function is being called on a const CBox
, or inside another const
method of that CBox
.
In this case, a const
after the member function name means the function itself is const
--basically, it means you cannot modify the object within the member function. The const before the member function means the return type is const
. (Though it can get complicated for return types, and I don't want to get into that here :) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With