Thursday, June 14, 2007

Const in C++

The const keyword in C++ is a very useful keyword . Apart from declaring constants it is useful in declaring few important things . Lets talk about two important const advantages
  1. pointer to a const
  2. const reference
Pointer to a const:
Pointer to a const basically says that the object being pointed to by the pointer should remain const and the pointer should not try to change the contents of that object . But this does not mean that that value of the object will not get changed m it just says the given pointer is not going to change the value of the object.

e.g String(const char * = ""){
.....
}

a simple rule of thumb is that if the function is not going to modify the object it should accept a const object

const reference:


void do_something(const Thing &);

This is analogous to pointers , the only advantage is that by declaring a reference const you prevent unnamed temporaries . Basically its the same concept which says if your not gonna change it then pass it as a const .

cannot use do_something(get_something()) // un named temporary not allowed

Things get_something();

Thing t(get_something());
void do_something(Thing&);

Const member functions:
const member function are member function in which the argument list is followed by the const keyword. In a const instance of an object only const member functions can be invoked.
From non const member functions unnamed temporaries can be invoked.

No comments: