0

So, moving from Linked List, I now have to build a Linked Stack, which I think is pretty much similar to it. However, I get an access error, saying that cannot access to private member which I do not understand, since I was not trying to access any private members at all....

LinkNode.h

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

template <class T>
class LinkedNode 
{

    public:

        LinkedNode(T newElement, unique_ptr<LinkedNode<T>> newNext):element(newElement), next(newNext ? new LinkedNode<T>newNext : nullptr)
        {
        }

        T GetElement() {return element;}

        void SetElement(T x) {element = x;}

        unique_ptr<LinkedNode<T>> newNext() {return next;}

        void SetNext(unique_ptr<LinkedNode<T>> newNext) {next = newNext;}

    private:
        T element;
        unique_ptr<LinkedNode<T>> next;
};

CompactStack.h

#pragma once
#include"LinkedNode.h"

using namespace std;

template <class T>
class CompactStack 
{

    public:

        CompactStack() {}
        bool IsEmpty() const { return head == 0; }

        T Peek() 
        {
            assert(!IsEmpty());
            return head-> GetElement();
        }

        void Push(T x) 
        {
            unique_ptr<LinkedNode<T>> newhead(new LinkedNode<T>(x, head));
            head.swap(newhead);
        }

        void Pop() 
        {
            assert(!IsEmpty());
            unique_ptr<LinkedNode<T>> oldhead = head;
            head = head->next();
        }

        void Clear() 
        {
            while (!IsEmpty())
            Pop();
        }

    private:
        unique_ptr<LinkedNode<T>> head;
};

This is the error that I've got from the compiler

Error   1   error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>' e:\fall 2013\cpsc 131\hw4\hw4\hw4\compactstack.h    23
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Hoang Minh
  • 1,066
  • 2
  • 21
  • 40

1 Answers1

1

Even if you are not directly accessing the unique_ptr, the default copy constructor of LinkedNode is accessing it. Now, a unique_ptr can be moved but not copied.

You have to define your own copy ctor such that you recreate the unique_ptr from the content pointed instead that by directly constructing one by copying the old.

This should help you.

Community
  • 1
  • 1
Jack
  • 131,802
  • 30
  • 241
  • 343
  • Could you explain a little more detail into that ? I've been reading the post that you are given and playing around with my code, but it is still not working yet.... – Hoang Minh Oct 08 '13 at 00:51