Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 😀

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading