0

For educational purposes I'm writing a templated Stack class based on a singly linked list. I have written a class for a node:

template <typename T>
class StackNode {
    private:
        T data;
        StackNode<T> *next;
        // TODO: make Stack a friend
};

and I started writing the stack itself:

template <typename T>
class Stack {
    private:
        StackNode<T> *head;
        unsigned long long int size;
    public:
        Stack(): head(nullptr), size(0) {}
        void push(const T& element) {
            StackNode<T> *new_element = new StackNode<T>;
            new_element -> data = element;
            new_element -> next = head;
            head = new_element;
            ++size;
        }
};

Obviously, these two lines

            new_element -> data = element;
            new_element -> next = head;

are giving me trouble, because I'm trying to get access to private members. I want to make Stack a friend of StackNode. How can I do that?

When I write friend class Stack<T> in my TODO line in the StackNode, my CLion IDE underlines Stack with a red squiggly line and it says that I have redefinition of Stack as a different kind of symbol. I don't know how to fix that.

UPD: my main function looks like this:

int main() {
    Stack<long long int> s;
    s.push(12);
    return 0;
}

I appreciate any help.

alekscooper
  • 795
  • 1
  • 7
  • 19
  • Why not define the class StackNode as struct in the private scope of Stack? Then you won't have that issue. No need for private member in StackNode then, because it is not visible to the outside anway. – lars Jan 03 '20 at 11:57
  • Furthermore you should show a minimal reproduceable example, since this won't work without forward declarations anyway. So we cannot be sure what you are doing wrong. – lars Jan 03 '20 at 11:59
  • @lars Again, for educational purposes I don't want to define StackNode as a struct. – alekscooper Jan 03 '20 at 12:00
  • @lars I added my main function. Now it's the full script. – alekscooper Jan 03 '20 at 12:02
  • For educational purpose it makes sense to choose a simple, good design. I think this not good "friend" example. – lars Jan 03 '20 at 12:15

1 Answers1

1

Well, your issue is still not reproducible / complete. If you want to such an issue to be solved, try an online compiler like wandbox. An example is complete, if you can copy paste it into an online compiler and it leads to the error, that you want to be solved.

We can only guess what your issue is. Maybe you missed the forward decl. This way a friend declaration is done with the same class dependency structure as in your example:

#include <iostream>

template<class T>
class Foo;

template<class T>
class Bar
{
public:
    Bar(T t) : v(t) {}

private:
    T v;
    friend class Foo<T>;
};

template<class T>
class Foo
{
public:
    void Fun(Bar<T> bar)
    {
        std::cout << bar.v;
    }
};

int main()
{
    Bar<int> bar(99);
    Foo<int> foo;
    foo.Fun(bar);
}
lars
  • 475
  • 2
  • 6