Search code examples
c++xcodeexc-bad-access

Control reaches end of non-void function overloading operator [];


#ifndef MyArray_hpp
#define MyArray_hpp
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#define MAX_ARRAY_SIZE 1000

using std::cout;
using std::endl;
using std::ifstream;
using std::cout;

//template class
template<typename NewType>
class MyArray
{

public:

    MyArray(size_t maxSize)
    { // constructor

        //(2)
        array_ = (NewType*) malloc(maxSize * sizeof(NewType));

    }

    void push_back(NewType item)
    {
        array_[size_] = item;
    } // push_back method
    class Iterator
    {

    public:

        Iterator(MyArray<NewType>* a, size_t s) :
                ptr(a), index(s)
        {
        }
        //(1) 
        NewType operator[](size_t i) const
        {   ptr->array_[i];}

    private:

        size_t index;
        MyArray<NewType>* ptr;

    };

    Iterator begin()
    {
        return MyArray<NewType>::Iterator(this, 0);
    }
    Iterator end()
    {
        return MyArray<NewType>::Iterator(this, size_);
    }

private:

    size_t size_;
    NewType* array_;

};

#endif /* MyArray_hpp */

So my issue is that in public " NewType operator[] " I get this error:

Control reaches end of non-void function

if I put return 0 at the end of it I get a second error in the class constructor at " array_ = (NewType*) ":

 Thread 1: EXC_BAD_ACCESS (code=1, address=0x504805ac0)

Ive been trying to fix this for a while now so help me figure out what I did wrong I looked up online and they said the latter error can be complicated to fix.


Solution

  • A function with a return type must return a value of that type.

    NewType operator[](size_t i) const { ptr->array_[i]; }
    

    has no return statement.

    Perhaps you meant

    NewType operator[](size_t i) const { return ptr->array_[i]; }
    

    ?

    I am unable to see error number 2

    array_ = (NewType*) malloc(maxSize * sizeof(NewType));
    

    but malloc is not something you should use in C++ outside a few rare edge cases. It allocates storage but does not invoke constructors. This makes a MyArray<std::string> a timebomb. Prefer to use new.

    Side note:

    void push_back(NewType item)
    {
        array_[size_] = item;
    } // push_back method
    

    Will always push to the same spot. You need to increment size_.

    Speaking of size_, it is never initialized, so you have no way to know where array_[size_] = item; will try to put item.