Explore BrainMass

C++ stack class with inheritance storing integers, strings

This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

Extend the improved stack class stack2 so that the derived class stack would be also capable to store integers, strings, or pairs of integers. Model the pair by a structure with two integer-valued fields x and y.

In the main program, define several integers, strings, and pairs and demonstrate pushing them to and popping from your stack.

© BrainMass Inc. brainmass.com March 21, 2019, 6:04 pm ad1c9bdddf


Solution Preview

Attached is C++ file plus an image of the results produced by the program. I have defined structure "Pair" to store pairs of integers (x,y). This is a simple realization of the stack and that in this type of stack it is a requirement that the pop command sequence is exact opposite of push command sequence. That is to say, if you pushed 1,"ABC",{1,2} you must pop {1,2},"ABC",1.

#include <iostream>
using namespace std;

class stack // a simple stack class
int top; // stack pointer
static const int MAX = 10; // stack size
int st[MAX]; // stack array
stack() // default constructor
top = -1;
void push(int n) // push method
st[++top] = n;
int pop() // pop method

Solution Summary

This solution provides a simple stack class that will store integers, strings and pairs of numbers. The program involves inheritance, where a more complicated stack2 class is inherited from base stack class.