AppreciateIt AppreciateIt - 1 year ago 66
C++ Question

Vector does not accept new element properly

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


when in reality I am expecting



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

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

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

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

From Main function

Node root = Node("root");
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download