C++ struct behavior

Viewed 127

I'm trying to improve my knowledge of the C++ language and am making a stack of stacks. Below is a very short example of my question: why do I have to directly access the members of the struct in order to change them instead of using functions to do that? If anyone knows why this happens a answer is very appreciated! Thanks

#include <iostream>
#include <vector>
using namespace std;

struct Stack {
    int N;
    vector<int> stack;

    int len() { return stack.size(); }

    void add(int N) { stack.push_back(N); }
};

struct Stacks {
    vector<Stack> stacks;

    Stack getStackAtIndex(int i) { return stacks[i]; }

    void addStack(Stack stack) { stacks.push_back(stack); }

    void printStacks() {
            cout << "Printing stacks" << endl;

            for (int i = 0; i < stacks.size(); i++) {
                    cout << "Stack #" << i << ": ";
                    for (int j = 0; j < stacks[i].len(); j++) {
                            cout << stacks[i].stack[j];
                            if (j != stacks[i].len()-1) cout << " -> ";
                    }   
                    cout << endl;
            }   
    }   
};

int main() {

    Stacks stacks;
    Stack stack;
    stack.add(1);
    stacks.addStack(stack);

    // This does not work:
    // stacks.getStackAtIndex(0).add(2);

    // This works:
    stacks.stacks[0].stack.push_back(2);

    stacks.printStacks();

    return 0;
}
2 Answers
Related