const

I just want to know that why do we use const and the begining of the function like
const char* func();

or const at the end of the function .
char* func( const char* name);
const char* is a pointer to a const char. It means we are not allowed to change what the pointer points to.
In both cases the const keyword is part of the data type. In the first sample, const char is the type for the pointer. Or in words, "func() returns a pointer to a constant character". This means that while the pointer variable itself is writeable, the char pointed to by its pointer value is constant. This means that you cannot const char *pVal = func(); pVal[0] = '3'; //Error! Constants cannot be changed. .

The second case is exactly the same thing but for the data type of the parameter. In the second case you are saying that "the function func() accepts one argument of type 'pointer to a constant char'", meaning the function will not be able to change the actual characters pointed to by the pointer.
closed account (1vRz3TCk)
const can also be used at the end of a member function to enforce/indicate that the function will not change the state of the object.


1
2
3
4
5
6
7
8
9
10
11
12
13
class Foo
{
public:
    void do_somthing() const;

private:
	int value; 
};

void Foo::do_somthing() const
{
    value = 6;  // Error value can not be changed here
}

Thanks CodeMonkey , webJose , Peter87 .. thanks all of you .. this clears my concept
Topic archived. No new replies allowed.