"A nested class has free access to all the static members of the enclosing class. All the instance members can be accessed through an object of the enclosing class type, or a pointer or reference to an object."
How can the members be accessed through an object of the enclosing class type? I understand the pointer and reference part because for them you dont need the full definition, but for creating a object you do?
Also it has free access to all static members because the nested class is part of the enclosed class and with static it exists in everything inside the enclosing class? Right or am I missing something?
nested class is a member of enclosing and have same access rights as any other member.
It basically a friend of enclosing class.
To access non-static members it should have an instance of enclosing class (because non-static members are unique for each instance and does not exist in global.)
// A push-down stack to store Box objects
#pragma once
class CBox; // Forward class declaration
class CStack
{
private:
// Defines items to store in the stack
struct CItem
{
CBox* pBox; // Pointer to the object in this node
CItem* pNext; // Pointer to next item in the stack or null
// Constructor
CItem(CBox* pB, CItem* pN): pBox(pB), pNext(pN){}
};
CItem* pTop; // Pointer to item that is at the top
public:
// Constructor
CStack():pTop(nullptr){}
// Push a Box object onto the stack
void Push(CBox* pBox)
{
pTop = new CItem(pBox, pTop); // Create new item and make it the top
}
// Pop an object off the stack
CBox* Pop()
{
if(!pTop) // If the stack is empty
returnnullptr; // return null
CBox* pBox = pTop->pBox; // Get box from item
CStack pTemp; // Save address of the top item
pTop = pTop->pNext; // Make next item the top // Delete old top item from the heap
return pBox;
}
// Destructor
virtual ~CStack()
{
CItem* pTemp(nullptr);
while(pTop) // While pTop not null
{
pTemp = pTop;
pTop = pTop->pNext;
delete pTemp;
}
}
};
Ignore everything else, but why does line 36 compile? CStack isn't completely defined?
Ok I just noticed that it is a function not a nested class but why does it work? Cause in a nested class like CItem it gives me a error that it is a incomplete type?