Well, there are many reasons you might use const...
Imagine you have a Game, so you have a window.
The window has a size, right?
When you declare it non-const, someone might think that he/she is allowed to change it's value.
So for example, you have a Window 640x480 and each frame you draw a grid
If someone sets the size to 320x480 the size of the window didn't change but the grid is only drawn in that area.
So, because that window size should be constant you declare it const.
Furthermore, in a function decleration, when not having the Keyword const before a pointer or reference you tell the compiler to give an error when a const variable is given as parameter.
Also, when you have a const-reference as parameter you may also use rvalues as parameters. (Most of the time when dealing with objects you want to pass them by reference, because it is faster)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Tree { int array[1000]; };
//...
void func(const Tree& tree) {} // save to call with every tree
void func2(Tree& tree) {} // this function may modify tree
void func2(Tree tree) {} // pass by value
int main(void)
{
// lvalues
const Tree tree;
func(tree); // valid
func2(tree); // invalid
func3(tree); // valid but needs to copy 1000 integers
// rvalues
func(Tree()); // valid
func2(Tree()); // invalid
func3(Tree()); // valid but needs to copy 1000 integers
return 0;
}
|