CStack Class

In this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 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
      return nullptr;                 // return null
        
    CBox* pBox = pTop->pBox;          // Get box from item
    CItem* pTemp = pTop;              // Save address of the top item
    pTop = pTop->pNext;               // Make next item the top
    delete pTemp;                     // 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;
    }
  }
};


Why is the destructor virtual? Isnt that useless in this situation? I know why they are used but in this situation isnt it useless?
Last edited on
Or is it just to represent good program design, because if any class is derived from CStack and made dynamic and pointed to by a base pointer it needs to also call its destructor.
closed account (zb0S216C)
Perhaps "CStack" is intended to be a base-class of some sort? Who knows? The author does.

Wazzak
Alright thanks!
Topic archived. No new replies allowed.