Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I need to know that how does to use "const" keyword within a function definition appropriately.
For an example:

const int * const function_name(const * int point) const;

const int*const Functiontwo(const int*const&)const;

Please explain each uses of const keyword for above function declaration.I grasped the basic idea but I wanted to know how to use them efficiently and why is the reason for those?
Posted
Updated 26-Aug-13 1:08am
v4
Comments
Buddhi Chaturanga 26-Aug-13 7:04am    
I gone through this web site:
[CLICK HERE]

but could not grasp the exact idea I wanted.Need better explanation how to put those "const" keyword appropriately on each place and how it affects to program efficiency.?

const is used either with a value or with a pointer.

In case of a value the story is simple: you put the const keyword in front of a function parameter declaration or a local/global variable that isn't a pointer or reference:
C++
const int j = 5;
void func(const in x)
{
    const float f = 0.5f;
}

I think the meaning of const in these cases is obvious.

Pointer/reference: I demonstrate just the pointers, const works the almost the same way for references (that are essentially pointers but you can/must initialize them exactly once when you declare them).
const int* and int const* mean the same: The int value or int array referenced by the pointer is constant. int* const means that the pointer variable itself is constant but the data referenced isn't! You can of course combine these: const int* const.

Now a special case comes: const method:
C++
class C
{
    void Method(int param) const
    {
    }
};

This isn't really a special case. The const after the method is used with the hidden this pointer parameter of the method.

So if the "pseudo code" of a normal non-const method looks like this:
C++
class C
{
    void Method(C* const this, int param)
    {
    }
};


then the "pseudo code" of a const method is the following:
C++
class C
{
    void Method(const C* const this, int param)
    {
    }
};

You simply can't write const there in front of the hidden this pointer so the language forces you to write that const after the method "header" declaration.

The this pointer value itself is always const even in case of non-const methods, you cant change the value of "this". By making a method const you mark the instance referenced by the this pointer as const. The result is that you can not call non-const instance methods from that const method and you can not modify the member variables of the instance because you have only a const C* const this pointer...

Wise use??? If you don't want someone to modify a value or data referenced by a pointer then declare it as const. Period. If you know that a method doesn't have to modify any member variables and it doesn't have to call other non-const members then declare the method as const. Typical example:
C++
class Array
{
public:
....
    size_t GetLength() const
    {
         // GetLength() doesn't modify anything inside the array and doesn't call non-const methods.
    }

    void Clear()
    {
        ...
    }
....
};

void Test(const Array& arr)
{
    // Because GetLength() is a const method you will be able to call that method on
    // a const Array pointer/reference/variable too! For this reason it is a good practice
    // to declare every method as const if it doesn't modify the instance, it enables you
    // to use those methods with const instances!
    arr.GetLength();
    
    // This causes a compile error because you try to call a non-const member on a const array.
    arr.Clear();
}


EDIT: avoid the usage of the mutable keyword that is basically a hack. I've seen maybe one place where it's usage was reasonable.
 
Share this answer
 
v3
Comments
Buddhi Chaturanga 26-Aug-13 7:34am    
thank you
pasztorpisti 26-Aug-13 10:41am    
You are welcome!
Buddhi Chaturanga 26-Aug-13 7:35am    
Can't you describe using the function I defined above:
const int*const Functiontwo(const int*const&)const;
Philippe Mori 26-Aug-13 8:27am    
The first 2 const apply to the return value, the next 2 apply to the parameter and the final one to the return value. Each case is already described in the answer.

By the way, you usually read everything backward in C++ so const int*const&`would be a reference to a constant pointer to an integer which is constant.

Well, int const would be a bit more consistent with that "reading" rule (the last part would be to a constant integer) but the usage is generally to put const first.

Almost any declaration can be read backward including array.
pasztorpisti 26-Aug-13 10:29am    
"By the way, you usually read everything backward in C++"
...or in worst case by progressing from the middle to the left and right sides... :-)
"reference to a const pointer that points to a const integer or integer array" - probably makes a beginner sick
Please refer to the first two solutions for explanation. I would like to add to these why you would or should not use const in particular places:

A) const int foo(); vs. int foo();
Doesnt't make sense: foo returns a value which can be assigned to a variable of type int. You can assign constants (such as 5) to an int variable as well as variables, so whether the return value type is declared const or not does not make a difference at all.

B) const int* foo(); vs. int* foo();
The result points to a location holding an int that may not (or may) be modified. Other pointers may be pointing to that same location, so it does make a difference whether you are allowed to modify it or not.

C) int* const foo(); vs. int* foo();
Nonsense for the same reasons as given in case A). The result type of the first form is a const pointer, but may be a assigned to a variable of type non-const pointer:
C++
int* const foo();
int* p = foo(); // valid assignment!
The second form is therefore equivalent (and less misleading).

D) int foo(const int);
For similar reasons as given in A) and C), there is no point for providing that const qualifier. All it does is prevent the implementation of foo to use the parameter as a variable. It does not prevent the implementation from copying that parameter into a non-const variable though.

E) int foo(const int*);
See B): the implementation of foo may read the value pointed to, but not modify it.

F) int foo(int* const);
See D): not particularly useful.

G) int foo(int* const&);
See F: not useful and also extremely confusing: the & means the parameter is passed by reference - something normally used to either pass a compound variable such as a struct, or to ensure the parameter may be modified and the modification will be seen by the caller (i. e. the parameter is used to hold an output value). Since the variable is both const, and not a compound, this doesn't make sense at all. (it is still 'legal' C++)

H) int foo() const;
Only legal for class functions, where it indicates that an instance of this class will not be modified by calling this function on it.


In short, in the examples provided by you, only three of the placements of const are really sensible, outlined in cases B), E) and H). The other uses of const, while legal, are not useful. You're better of not using const in these cases.
 
Share this answer
 
v2
A simple trick to understand is

C++
const char *ptr = &someVariable;

see *ptr, which as normal usage signifies data. So data is constant. i.e you have a pointer pointing to a constant data. You cannot do something like
C++
char var = 'a';
const char *ptr = &var;

*ptr='c';//not allowed
*ptr++;//not allowed

//but you could do
var = 'x';//or
ptr = &someOtherVariable;


now secondly
C++
char* const ptr = &var;
//see the const is after the * signifying that your pointer is constant. Meaning it will point to one location only.

ptr= &someOtherVariable; //not allowed
ptr++; //not allowed

//but the following is allowed
*ptr= 'x';
*ptr++; 


so for a pointer to be truely constant, by which I mean it points to a fixed location and the value at that location cannot be changed can only be achieved by doing this :
C++
const char* const ptr; //constant pointer to a constant value


as for use of const as below
C++
int function(const SomeClass& abc) const;

means we have a function that takes SomeClass as a const reference. And the const at the end of the function signifies that the function does not mutate any data members (unless you have a mutable data member).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900