Home > Software engineering >  Passing array of class objects
Passing array of class objects

Time:11-05

I've been trying for a long time to pass an array of objects to another class object.

In settingUp.cpp:

//** Status classes and their functions **//
void settingUp(){

    dataClass prueba0;
    dataClass prueba1;
    dataClass prueba2;

    const dataClass * arrayPrueba[3];

    prueba0.setValues(1);
    prueba1.setValues(2);
    prueba2.setValues(3);

    arrayPrueba[0] = &prueba0;
    arrayPrueba[1] = &prueba1;
    arrayPrueba[2] = &prueba2;

    statusClass status;
    status.setValues(1, arrayPrueba);

    status.printValues();
}

In classData.cpp:

//** dataClass and their functions **//

void dataClass::setValues(int _length){
    
    length = _length;
}

void dataClass::printValues() const{

    printf("TP: dataClass: length = %d\n", &length);
};

In statusClass.cpp:

//** Status classes and their functions **//
void statusClass::setValues (uint8_t _statusSelectorByte, const dataClass **_array){

    newStatusSelectorByte =     _statusSelectorByte;
    array = *_array;
};

void statusClass::printValues(){

    printf("TP: statusClass -> printValues: Prueba = %d\n", newStatusSelectorByte);
    printf("TP: statusClass -> printValues: arrayPrueba = %d\n", array[1].length);  
}

When I call:

status.printValues();

I can read only the fist element of the arrayPrueba.

CodePudding user response:

In statusClass::setValues(), *_array is the same as _array[0]. You are storing only the first dataClass* pointer from the input array.

Later, when using array[1], you are mistreating array as-if it were a pointer to an array of objects, when it is really a pointer to a single object instead. You are thus reaching past that object into surrounding memory, which is undefined behavior (but may "work" in this case because an object may happen to actually exist at that location, but this is bad behavior to rely on).

You need to store the original array pointer, not a single element taken from the array.

private:
    const dataClass **array; // <-- add an *

void statusClass::setValues (uint8_t _statusSelectorByte, const dataClass **_array){

    newStatusSelectorByte =     _statusSelectorByte;
    array = _array; // <-- get rid of the *
};

void statusClass::printValues(){

    printf("TP: statusClass -> printValues: Prueba = %d\n", newStatusSelectorByte);
    printf("TP: statusClass -> printValues: arrayPrueba = %d\n", array[1]->length);  // use -> instead of .
}

On a side note: in dataClass::printValues(), you need to drop the & when printing the value of length:

printf("TP: dataClass: length = %d\n", length);
  • Related