Operator[] overload: Why do I have to define it as const function

I am trying to replicate a vector in my myVec class.

When I declare the subscript operator [] overload as non-const, and use it in ostream << operator overload friend function, I get a compiler error saying that I am calling a non-const member function from a const instance. (the argument to ostream operator overload is a const reference to my myVec object.

The above is expected. However, when I check the std::vector and std::string operator [] function signatures, they are non-const functions.

What is the standard way of implementing this? Should I change my ostream operator<< overload signature to take a non-const reference? My code is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>
#include <cassert>

template <class T>
class myVec
{

private:
    T      *head;
    size_t length;

public:

    myVec()
    {
        length = 0;
        head = 0;
    }

    // allocate memory for vector and initialize the values
    myVec( size_t len, const T &val )
    {
        head = new T[len];
        for ( size_t i = 0; i < len; i++ )
            head[i] = val;
        length = len;
    }

    size_t size() const { return length; }

    //When I make this non-const I get an error in the ostream << function
    T& operator[]( size_t index ) const
    {
        assert (index >= 0 && index < length);
        return head[index];
    }

    // free the unnecessary memory
    void clear()
    {
        std::cout << "Clear Called with length = " << length << "\n";
        delete [] head;
        length = 0;
    }
    ~myVec()
    {
        clear();
    }

    template <class J>
    friend std::ostream& operator<< ( std::ostream& os, const myVec<J> &v );

};

template <class U>
std::ostream& operator << ( std::ostream& os, const myVec<U> &v )
{
    size_t len = v.size();
    for ( size_t i = 0; i < len; i++ )
        os << v[i] << " ";
    os << "\n";
    return os;
}

int main()
{
    myVec<int> v1( 10, 11 );
    std::cout << v1;
    std::cout << "Finished!\n";
    return 0;
}


Thanks!
Last edited on
The standard way is to have two versions. One const and one non-const version. That's how std::vector and std::string does it.
Oh, yes Thanks!
I missed the const versions in the std::vector and string implementations :)
Topic archived. No new replies allowed.