Pass the array of objects in the member function

advertisements

Here is the class defination:

class Unit
{
    public:
     Unit();
     ~Unit();
     void set_unit(int a);
     void modify_flag(Unit&);
     void modify_array(Unit array[], int len);  // ?? The problem
     int show_unit();

    private:
     int ai;

};

And the implementation of the member functions:

void Unit::set_unit(int a)
{
     ai = a;
}

void Unit::modify_flag(Unit& u)
{
     u.set_unit(20);
}

void Unit::modify_array(Unit array[], int len)  // ?? The problem
{
     for (int i = 0; i < len; ++i)
     {
        modify_flag(array[i]);
        array[i].modify_array(array, len);
     }
}

int Unit::show_unit()
{
    return ai;
}

And finally the main code:

int main(int argc, char const *argv[])
{
    int len = 10;
    Unit* array = new Unit[len];

    for (int i = 0; i < len; ++i)
    {
        array[i].set_unit(0);
    }

    array[5].modify_array(array,len);  // ?? The problem

    for (int i = 0; i < len; ++i)
    {
        cout << array[i].show_unit() << endl;
    }

    delete [] array;

    return 0;
}

I passed an array of objects into the member function of the class as the parameter, but it aborted suddenly. I have checked my code many times to make sure the counter did not accumulate over the array length. Therefore, I think there must be something wrong with the object array as the parameter, but I could not figure it out. What happened with my code ??


You have uncontrolled recursion.

In modify_array the program will call

array[i].modify_array(array, len);

len times, each of which will call

array[i].modify_array(array, len);

len times, each of which will call

array[i].modify_array(array, len);

len times, each of which will call

array[i].modify_array(array, len);

len times...

You should be able to see where this is going.

Unfortunately, I'm not sure what your goal is so a can't suggest a proper solution, but You must have some exit condition to stop the chain of calls before you run out of automatic storage (most likely stack space).

For example you could

void Unit::modify_array(Unit array[], int len)  // ?? The problem
{
     for (int i = 0; i < len; ++i)
     {
        modify_flag(array[i]);
        array[i].modify_array(array, len - 1); // note the -1
     }
}

so that every iteration looks at less of the array. Eventually len will be 0 and i < 0 will result in no further calls. What good this does you, I can't say, but it stops the recursion.

Do you need the recursion at all? I don't know.