When to declare a member function as 'const'

I do not know the correct word for it - but I am trying to describe the unusual situation where you declare a class member function with this format:

 
bool class::function_name(void) const


Specifically where the 'const' follows the parameter list. It is my understanding this is a very useful way of ensuring that whatever code you put in the function definition cannot change any data members of its class.

However I have recently read that this form of declaration should not be used as it leads to less optimized and slower code. Is this correct? If so could someone explain to me why this is the case?
Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. A constant member function cannot modify any non-static data members or call any member functions that aren't constant.
To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition.

http://msdn.microsoft.com/en-us/library/6ke686zh.aspx
http://www.parashift.com/c++-faq/const-member-fns.html

By the way I wouldn't be too worried about it slowing down code. I don't think that is the case but even if it does it is probably nano-seconds. It probably takes the same amount of time as it does to cast from say an int to a const int.
However I have recently read that this form of declaration should not be used as it leads to less optimized and slower code. Is this correct?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

struct Square
{
  int edge_length;

  int area( void ) { return edge_length * edge_length; };
};

void printArea( const Square& square )
{
  std::cout << square.area() << '\n';
}

int main( void )
{
}


1
2
3
main.cpp: In function 'void printArea(const Square&)':
main.cpp:12:28: error: passing 'const Square' as 'this' argument of 'int Square::area()' discards qualifiers [-fpermissive]
   std::cout << square.area() << '\n';


Square::area() should be const qualified because we want to be able to use it when we have a constant Square.
Many thanks chaps! Those examples do clear up a lot of my questions - especially the case where you return a reference. In other situations I could see that being a very clever way to make the modification of a data member possible by the calling function - rather like an array with '[]'. However the 'const' prevents that happening - cool!

I was told about the lack of optimization on 'stack overflow'. I don't post there any more.
Last edited on
Topic archived. No new replies allowed.