const function what for?

What's the purpose of adding const to a function?

 
  const_iterator begin() const { return data; }


I'm returning data so what's the difference if I ommit const? I don't understand what's used for..
Last edited on
> What's the purpose of adding const to a function?

See: https://isocpp.org/wiki/faq/const-correctness#const-member-fns


non-const container: iterator begin(); returns a mutable iterator.
Using the iterator returned by begin(), the elements in the container can be modified.

const container: const_iterator begin() const ; returns a non-mutable iterator
Using the iterator returned by begin(), the elements in the container can be accessed, but not modified.
What's the difference here?

1) const_iterator begin() const { return data; }
2) iterator begin() const { return data; }

Both are const?
This is const-correct:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct A
{
    using iterator = int* ;
    using const_iterator = const int* ;

    // const-correct
    iterator begin() { return data ; }
    const_iterator begin() const { return data ; }

    iterator end() { return data+N ; }
    const_iterator end() const { return data+N ; }

    static constexpr std::size_t N = 6 ;
    int arr[N] { 0, 1, 2, 3, 4, 5 } ;
    int* data = arr ;
};

void const_correct( const A& a )
{
    auto iter = a.begin() ;
    std::cout << *iter << '\n' ; // fine
    // *iter = 100 ; // *** error (as it should be): non-mutable iterator
                     // the const object can't be modified
}


This isn't:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct B
{
    using iterator = int* ;

    // this is not const-correct
    iterator begin() const { return data ; }
    iterator end() const { return data+N ; }

    static constexpr std::size_t N = 6 ;
    int arr[N] { 0, 1, 2, 3, 4, 5 } ;
    int* data = arr ;
};

void not_const_correct( const B& b )
{
    auto iter = b.begin() ;
    std::cout << *iter << '\n' ; // fine
    *iter = 100 ; // compiles cleanly: but this is terrible
                  // a const object is being modified
}
Topic archived. No new replies allowed.