Home > Mobile >  I can change the values even when I use const word with my own array class template
I can change the values even when I use const word with my own array class template

Time:10-18

So I'm trying to write my own array template and everything works until i try to create a const object of my class template. in main.cpp I create the object with the copy contructor and I change it which I would expect to not work but it works. Help would be appreciated :D

main.cpp

# include "Array.hpp"

int main( void ) {

    Array<int> l = 1;
    l.setValue(5, 0);


    const Array<int> abc(l);
    std::cout << abc[0] << std::endl;
    abc[0] = 3;
    std::cout << abc[0] << std::endl;

    return (0);
}

Array.tpp

#ifndef ARRAY_TPP
# define ARRAY_TPP

# include "Array.hpp"

template<class T>
class Array {
private:

    int size_;
    T *array_;

public:
    Array() : size_(0), array_(new T[size_]) {};

    Array(int n) : size_(n), array_(new T[size_]) {};

    Array(Array const& src) : size_(src.size()), array_(new T[src.size()]) {
        for (int i = 0; i < src.size();   i) {
            array_[i] = src[i];
        }
    };


    Array& operator=(Array const& copy) {
        size_ = copy.size();
        delete[] array_;
        array_ = new T[size_];
        for (int i = 0; i < size_; i  )
            array_[i] = copy[i];
        return (*this);
    }

    T& operator[](int n) const {
        if (n < 0 || n >= size_)
            throw std::out_of_range("out of range");
        return (array_[n]);
    }


    int size(void) const { return (size_); };

    void setValue(T value, int n) {
        if (n < 0 || n >= size_)
            throw std::out_of_range("out of range");
        array_[n] = value;
    }

    ~Array() { delete[] array_; };
};

#endif

CodePudding user response:

The issue is this:

T& operator[](int n) const {
    if (n < 0 || n >= size_)
        throw std::out_of_range("out of range");
    return (array_[n]);
}

Because this is declared to be a const method, it can be called on a const Array. Though, it returns a non-const reference to the element. Because Array stores the elements via a T *, only that pointer is const in a const Array while modifiying the elements via that pointer is "fine".

You need two overloads of operator[]:

 T& operator[](int n);
 const T& operator[](int n) const;
  • Related