This C++ program illustrates the use of nested classes. The program uses Node class as a member for Stack class where Node class is nested inside Stack class. The Node class is local to Stack class which can be used outside Stack’s context by using scope operator ‘::’.
Here is the source code of the C++ program illustrates the use of nested classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Illustrate Nested Classes
*/
#include <iostream>
class Stack {
class Node {
public:
int data;
Node* next;
Node(int data, Node* next);
~Node();
}* head;
public:
Stack();
Stack(const Stack& s);
void operator=(const Stack& s);
~Stack();
void push(int data);
int peek() const;
int pop();
};
Stack::Node::Node(int data, Node* next)
{
this->data = data;
this->next = next;
}
Stack::Node::~Node() { }
Stack::Stack() { head = NULL; }
Stack::Stack(const Stack& s)
{
head = s.head;
}
void Stack::operator=(const Stack& s)
{
head = s.head;
}
void Stack::push(int data)
{
head = new Node(data, head);
}
int Stack::peek() const {
if(head == 0)
{
std::cerr << "Stack empty!" << std::endl;
return -1;
}
else
return head->data;
}
int Stack::pop()
{
if(head == NULL) return -1;
int result = head->data;
Node* oldNode = head;
head = head->next;
delete oldNode;
return result;
}
Stack::~Stack()
{
if(head != NULL)
{
while(head->next != NULL)
{
Node* temp = head;
head = head->next;
delete temp;
}
}
}
int main()
{
Stack Integers;
int value, num;
std::cout << "Enter the number of elements ";
std::cin >> num;
while(num > 0)
{
std::cin >> value;
Integers.push(value);
num--;
}
while (( value = Integers.pop() ) != -1)
std::cout << "Top element of stack " << value << std::endl;
}
$ a.out Enter the number of elements 5 1 2 3 4 5 Top element of stack 5 Top element of stack 4 Top element of stack 3 Top element of stack 2 Top element of stack 1
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Computer Science Books
- Apply for Information Technology Internship
- Practice Computer Science MCQs
- Practice Programming MCQs
- Buy Programming Books