i can't understand the sense of const qualifier

hello everybody......
I am studying refernce to const and pointer to const but I can not understand what sense is ........ if we use a reference to a const or if we use a pointer to const I understand completely restrict the operations possible with pointers and references ..... I have recently begun studying pointers and references and would like help.


could you explain to me why use a const reference to refer to an object if we can not then use that reference to indirectly change the subject? or why use a pointer to const if we can not change the value of the object to which the pointer points? I have also studied the const pointers and also I can not understand .... I know that with pointers and references can be made for other operations but having now studying only those basic I seem to render them useless by the const qualifier ......

maybe I will need in the future?




could you explain to me why use a const reference to refer to an object if we can not then use that reference to indirectly change the subject?

There is no such thing as a const reference. You had it right in the first paragraph. A reference to const is used because we want to guarantee no changes are made to the original object. The same reasoning applies to pointers to const. The answer is in the question.

There is also the fact that a temporary will bind to a reference to const, but not a regular reference.

For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// http://ideone.com/xA1O1L
#include <iostream>
#include <string>

void print_indented_const(std::size_t dist, const std::string& s)
{
    std::cout << std::string(dist, ' ') << s << '\n' ;
}

void print_indented(std::size_t dist, std::string& s)
{
    print_indented_const(dist, s);
}

int main()
{
    print_indented(5, "some text");  // illegal
    print_indented_const(5, "some text");  // legal
}

Last edited on
pieroborrelli wrote:
could you explain to me why use a const reference to refer to an object if we can not then use that reference to indirectly change the subject?


Passing by reference (and by pointer) is faster than passing by value.
So you can think of passing by reference to const as a performance tweak.
beside optimization opportinity, not everything may be passed by value, and passing by reference allows runtime-polymorphic use.
Topic archived. No new replies allowed.