Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class and struct nesting

Tags:

c++

class

struct

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?

like image 919
user1279988 Avatar asked Dec 16 '22 02:12

user1279988


2 Answers

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".

like image 122
Luchian Grigore Avatar answered Dec 18 '22 16:12

Luchian Grigore


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.

like image 34
Alok Save Avatar answered Dec 18 '22 15:12

Alok Save