Guys, Sory if its a silly questionn.I have been trying to fix it for hours now.I get a weired segmentation fault.
Basically, I have a Stack class, It works fine.I then have a Queue class which instantiates a Stack class.So when I create the Queue class I get a segfault.
// this is the queue.cpp
template <class T>
Queue<T> :: Queue()
{
Stack<T>* stack = new Stack<T>();
// stack->pop;
}
template <class T>
Queue<T> :: ~Queue()
{
delete stack;
}
// this is the main I test the queue
// Stack<int> stack;
Queue<int > q; // The error occurs here.
/* stack.push(4);
stack.push(7);
stack.push(3);
stack.push(1);*/
return 0;
In the Queue constructor you create a temporary variable stack which hides the class variable of the same name, so the actual class variable is uninitialized. The memory allocated in the constructor is leaked, and you attempt to delete memory you don't own in the Queue destructor.
A segmentation fault usually occurs because you try to access memory that you don't own.
You access memory you don't own by using a bad pointer.
In your case, the stack member variable appears to be a bad pointer. Why?
Because in your constructor, you declare a local variable named stack, and you don't change the actual member variable.
The benefit of using initialization lists is that the member data is initialized at its construction, instead of being assigned to after its construction. This saves a step, and in some cases can speed up the program.
Is there any need to dynamically allocate that Stack object? It's created when the Queue is created, and destroyed when the Queue is destroyed. In other words, its lifetime is exactly the same as the Queue object it belongs to.
Why not simply make the object itself a member of the class, rather than using a pointer and dynamically allocating?