Koji
Koji

Reputation: 23

C++ class member: Why does class member return different value from second access?

I'm new to C++, and wrote NumberStack class in stack.cpp as follows, but the result is different from what I expected, So I need your help:

#include <iostream>

class LinkedListNode {
    public:
        int value;
        LinkedListNode* next;

        LinkedListNode(int initialValue) {
            value = initialValue;
        }
};

class NumberStack {
    public:
        LinkedListNode* head;

        NumberStack(int initialValue) {
            LinkedListNode node(initialValue);
            node.next = NULL;
            head = &node;
        }

        void push(int initialValue) {
            LinkedListNode node(initialValue);
            node.next = head;
            head = &node;
        }

        int top() {
            return head->value;
        }
    private:
};

int main() {
    NumberStack myStack(6);
    myStack.push(2);
    myStack.push(5);

    std::cout << myStack.top() << "\n";
    std::cout << myStack.top() << "\n";
    std::cout << myStack.top() << "\n";

    return 0;
}

When executing this file, I got output like this:

$ g++ stack.cpp
$ ./a.out
5
45264732
45264732

I expected output would be like this.

5
5
5

So what caused this? I'm using MacOS Big Sur

Upvotes: 2

Views: 63

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

There are three changes that you need to make:

  • Initialize node's `next' in the constructor
  • Initialize head to nullptr
  • Allocate nodes dynamically

Here is how:

LinkedListNode(int v, LinkedListNode* n = nullptr): value(v), next(n) {}

Then call

head = new LinkedListNode(initialValue, head);

I would also give NumberStack a default constructor, rather than a constructor that takes the initial value.

Upvotes: 1

Related Questions