Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of method return types and modifiers in C++ important?

Tags:

c++

visual-c++

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

like image 845
Scott Davies Avatar asked Mar 10 '11 21:03

Scott Davies


2 Answers

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.

like image 143
Nate Avatar answered Sep 27 '22 21:09

Nate


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 :) )

like image 29
dappawit Avatar answered Sep 27 '22 21:09

dappawit