Reputation: 77
I'm implementing a stack using two queues as an exercise. I have two queue objects in every instance of a stack class. I would like the destructor of the stack to call the destructor of the queues. Looking online, it seems that explicit usage of destructors is not very common as they tend to be called automatically. My code:
template<class T>
class Stack {
// LIFO objects
public:
Stack(int MaxStackSize = 10);
~Stack();
bool IsEmpty() const {return addS.IsEmpty();}
bool IsFull() const {return addS.getSize()==maxSize;}
Stack<T>& Add(const T& x);
Stack<T>& Delete(T& x);
void Print() const;
private:
LinkedQueue<T> addS;
LinkedQueue<T> delS;
int maxSize;
};
template<class T>
Stack<T>::Stack(int MaxStackSize)
{
maxSize = MaxStackSize;
}
template<class T>
Stack<T>::~Stack()
{
~addS();
~delS();
}
template<class T>
class LinkedQueue {
// FIFO objects
public:
LinkedQueue() {front = rear = 0;} // constructor
~LinkedQueue(); // destructor
bool IsEmpty() const
{return ((front) ? false : true);}
bool IsFull() const;
T First() const; // return first element
T Last() const; // return last element
LinkedQueue<T>& Add(const T& x);
LinkedQueue<T>& Delete(T& x);
void Print() const; // print the queue in order
int getSize() const;
private:
Node<T> *front; // pointer to first node
Node<T> *rear; // pointer to last node
};
template<class T>
LinkedQueue<T>::~LinkedQueue()
{// Queue destructor. Delete all nodes.
Node<T> *next;
while (front) {
next = front->link;
delete front;
front = next;
}
}
Running the above code gives me the following error:
stack.h: In destructor ‘Stack< T >::~Stack() [with T = int]’: stackrunner.cc:9: instantiated from here stack.h:37: error: no match for call to ‘(LinkedQueue< int >) ()’
Am I calling the destructors incorrectly? Should I not be calling the destructors at all? Are object destrcutors called automatically when the class destructor is called?
Upvotes: 0
Views: 1528
Reputation: 145194
Destructors are called automatically for you.
Calling a destructor on an already-destroyed-object is Undefined Behavior. It may crash, or lead to arbitrary results, or do real damage.
As a rule, never call a destructor explicitly (unless you have been using placement new to construct an object in existing storage).
Upvotes: 4