AppreciateIt AppreciateIt - 2 months ago 10
C++ Question

Vector does not accept new element properly

I see some odd behaviour in the code below. My console is printing


0lo1lo


when in reality I am expecting


0Hel1lo


Node.cpp

std::vector<Node> Node::getChildren() {
return children;
}

void Node::setChildren(std::vector<Node> childrenNodes) {
children = childrenNodes;
}

void Node::addChild(Node child) {
children.push_back(child);
std::cout << child.getTitle();
}

std::string Node::getTitle() {
return title;
}


From Main function

Node root = Node("root");
root.addChild(Node("Hel"));
root.addChild(Node("lo"));
std::cout << "\n";
std::vector<Node> children = root.getChildren();
for (int i = 0; i < children.size(); i++) {
Node menuItem = children[i];
std::cout << i;
std::cout << menuItem.getTitle();
}
std::cout << "\n";


Does anybody have an idea why getChildren() appears to be getting a vector that is not accurately listing the first element I inserted?

Answer

You're using global variables to store instance data:

std::string title;

That means there's only one title in your program and if you ever change it, it changes for every class, function, etc. that accesses it.

Make it a non-static member variable of Node and your problem will go away.