1

I'm trying to recreate the vector class in C++

I obtain this error int the function at();

invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'

Isn't it possible to return a pointer as address even if the function is supposed to return a reference?

the code looks like:

template<typename T> class Vector { public: explicit Vector(int initSize = 0); Vector(const Vector & rhs) throw (std::bad_alloc); ~Vector(); const Vector & operator=(const Vector & rhs) throw (std::bad_alloc); void resize(int newSize); void reserve(unsigned int newCapacity); bool empty() const; int size() const; int capacity() const; T & operator[](int index); const T & operator[](int index) const; T & at(int index) throw (std::out_of_range); void push_back(const T & x) throw (std::bad_alloc); T pop_back(); const T & back() const; typedef T * iterator; typedef const T * const_iterator; iterator insert(iterator it, const T& x) throw (std::bad_alloc); iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; private: int theSize; unsigned int theCapacity; T * objects; }; #include "vector.hpp" #endif /* VECTOR_HPP_ */ template<typename T> Vector<T>::Vector(int initSize):theSize (initSize),theCapacity(128),objects(0) { } typename Vector<T>::iterator Vector<T>::begin() { return objects; } template<typename T> T & Vector<T>::at(int index) throw (std::out_of_range) { //if (index<=theSize) return (begin()+index); } int main() { Vector<int>* vec1=new Vector<int>(4); cout<<vec1->at(2)<<endl; return 0; } 
3
  • You should be using Vector<int> vec1(4); in main. Commented Sep 15, 2013 at 1:24
  • Just from the guts (tl;dr;): Propably a superflous & or missing * somewhere .. Commented Sep 15, 2013 at 1:26
  • at() returns a reference. begin() + index is pointer arithmetic, evaluating to an address. You need to return *(begin() + index), and I highly advise you range-check that first, and throw an exception if its out of bounds. And note, unless you want to support negative offsets, and I can't imagine you do, your index parameter should be unsigned. Commented Sep 15, 2013 at 1:30

1 Answer 1

2

The expression begin()+index is of pointer type; you need to add a dereference to make it a reference:

template<typename T> T & Vector<T>::at(int index) throw (std::out_of_range) { return *(begin()+index); } 

Note that this may not be safe, because operations that re-allocate objects would invalidate the reference obtained through the at() function.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.