mercredi 4 septembre 2019

Initializing a member variable in a constructor

I get an error in the stack.cpp file on this line of code:

stack::stack()

The error says that the variable stack::el is uninitialized. Always initialize a member variable (Type 6). Can somebody help me understand the problem here please? Do I need to fix the problem in the cpp file or in the header file?The application is to push and pop elements onto and off of a stack.

#include <iostream>
#include "Stack.h"
using namespace std;

stack::stack() //stack class constructor
{
    top = -1; // start out with an empty stack represented by -1 
}

stack::~stack()  //destructor
{

}

bool stack::isEmpty() { //Function to determine if the stack is empty
    if (top == -1) { 
        return true; 
    } else {
        return false;
    }
}

bool stack::isFull() { // Function to determine if the stack is full
    if (top == MAX - 1) {
        return true;
    }   else {
        return false;
    }
}

void stack::push(el_t elem) { //Function to push an element onto the top of the stack
    if (isFull()) {
        // lookup exception handling document
    }
    else {
        top++; el[top] = elem;
        cout << elem << " pushed onto the stack" << endl;
    }
}

void stack::pop(el_t& elem) { //Function to pop the top element from the stack, using pass by reference
    if (isEmpty()) {
        //underflow exception handling
    } else {elem = el[top]; top--;}
}

void stack::displayAll() //Function to display all elements in the stack
{
    if (isEmpty()) {
        cout << "Stack is empty" << endl;
    }
    else {
        for (int i = top; i >= 0; i--)
            cout << el[i] << endl;
    }
}

void stack::topElem(el_t& elem) //Function to get the top element of a stack
{
    if (isEmpty()) {
        //underflow exception handling
    }
    else {
        elem = el[top];
    }
}

void stack::clearIt()
{
    el_t temp = 'a';
    cout << "Clearing the stack..." << endl;
    while (!isEmpty()) {
        pop(temp);
    }
}

This below is my stack.h header file

using namespace std;

const int MAX = 10;
typedef char el_t;

class stack {
private: // Private data members are:
    el_t el[MAX];               // el is an array with slots 0 .. MAX-1
    int  top;                   // the index to the top element

public: // Public Prototypes follow:

    stack();
    ~stack();

    bool isEmpty();
    bool isFull();
    void push(el_t);
    void pop(el_t&);
    void displayAll();
    void topElem(el_t&);
    void clearIt();
};

Aucun commentaire:

Enregistrer un commentaire