I am trying to return a Cell array item from the Table class using a get function. The Cell class has its own set function.

I tried by just making a Cell array and getting and setting the attributes. It worked, but for some reason it doesn't work here.

class Cell {
    int content;
    ...
public:
    Cell() {
        content = 0;
        ...
    }
    int getContent() {
        return content;
    }
    void setContent(int x){
        content = x;
    }
};

class Table {
    Cell cells[10];
public:
    Table() {}

    Cell getCell(int i) {
        return cells[i];
    }
};

int main () {
    Table t;
    t.getCell(0).setContent(22);
    std::cout<<t.getCell(0).getContent();
}

I was expecting to get 22 but the program outputs nothing.

2 Answers

3
Blaze On Best Solutions

This is because here

Cell getCell(int i) {
    return cells[i];
}

You're returning a copy of the Cell. You then change its contents, but those are lost when the copy goes out of scope. getCell(0) makes a copy that is discarded at the end of this line. Instead you want to return a reference to the cell:

Cell& getCell(int i) {

Now it's changing the contents of the Cell in cells[10], not a copy thereof.

0
eMazarakis On

You can try sth like this :

Cell* getCell(int i) {
   return &cells[i];
}


t.getCell(0)->setContent(22);
std::cout<<t.getCell(0)->getContent();