user1279988
user1279988

Reputation: 763

class and struct nesting

I am not very clear about this code

outer is a class and the inner a struct, can anyone help me explain it?

class Stack {
    struct Link {
        void* data;
        Link* next;
        Link(void* dat, Link* nxt):
        data(dat),next(nxt) {}
    }* head;
public:
    Stack():head(0) {}
    ~Stack() {
        require(head==0,"Stack not empty");
    }
    void push(void* dat) {
        head = new Link( dat, head );
    }
    void peek() const {
        return head ? head->data : 0;
    }

    void* pop() {
        if(head == 0)  return 0;
        void* result = head->data;
        Link* oldHead = head;
        head = head->next;
        delete oldHead;
        return result;
    }
};

my question is focus on the first few lines

class Stack {
    struct Link {
        void* data;
        Link* next;
        Link(void* dat, Link* nxt):
        data(dat),next(nxt) {}
    }* head;

what the relation between class Stack and struct Link?

Upvotes: 4

Views: 6202

Answers (3)

Boris Strandjev
Boris Strandjev

Reputation: 46943

Struct Link is inner-declared in the class (the correct term is nested). It can be accessed only in the class (due to its default private accessor level). The struct could have been referred with Stack::Link if it was declared public.

The reason for such declaration in this case is that only the inner methods of the class need to use the links and struct is providing better code organization. However as long as no other class needs to access the struct such declaration provides better encapsulation.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206518

Class Stack and struct Link are nested.
Note that nested classes have certain limitations regarding accessing of elements of nested and the enclosing class.

Since, Link is declared under private access specifier in class Struct it cannot be accessed outside the class Struct.

Upvotes: 5

Luchian Grigore
Luchian Grigore

Reputation: 258568

Link is declared inside Stack, and since it's private by default, it can't be used outside the class.

Also, Stack has a member head which is of type Link*.

The only difference between class and struct is the default access level - public for struct and private for class, so don't let "struct declared inside a class" confuse you. Other than the access level, it's the same as "class declared inside a class" or "struct declared inside a struct".

Upvotes: 6

Related Questions