Debug assertion failed - Copy constructor - Delete operttion

I get debug assertion failed when trying to run this program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include "Stackt.h"
#include "Stackt.cpp"

void main()
{
	int N;
	cin >> N;
	Stackt<int> Source, S;
	for (int i = 0; i < N; i++)
		Source.push(i + 1);
	int temp;
	S = Source;
	for (int i = 0; i < N; i++)
	{
		S.pop(temp);
		cout << temp << endl;
	}
}


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
// File: Stackt.cpp
// Stack template class implementation

#include <iostream>
using namespace std;
#include "Stackt.h"
// Constructor with argument, size is nelements, default is 128
template <class Type>
Stackt<Type>::Stackt(int nelements)
{
	MaxSize = nelements;
	stack = new Type[MaxSize];
	top = -1;
}

// Copy Constructor
template <class Type>
Stackt <Type> ::Stackt(const Stackt<Type> 	&original)
:MaxSize(original.MaxSize), top(original.top)
{
	stack = new Type[MaxSize];
	for (int i = 0; i <= top; i++) stack[i] = original.stack[i];
}


//Destructor
template <class Type>
Stackt<Type>::~Stackt()
{
	delete [] stack;
}


After doing some search and trying a little bit I found that the problem related to the line:
S = Source;
If I remove it, the problem is gone. I also think this may be related to the copy constructor and destructor. Any help would be appreciated
The copy constructor is not used on the line in question. The copy assignment operator is used, but it looks like you have not defined it.

By the way, don't use .cpp files with template classes.
Last edited on
Nothing wrong with template classes in .cpp file as long as its specific to that implementation file.
Thanks for the replies

Yeah someone told me it's better to put them in the .h file


Now regarding the copy assignment operator shouldn't it be something like

Stackt<Type> Stackt<Type>::operator = (Stackt<Type> A, Stackt<Type> B)
{
//Do something
}

Any help of the do something part. I guess there should be a new pointer to Type and then I make the contents the same, right?
Now regarding the copy assignment operator shouldn't it be something like

Since you already have a working copy constructor, you can leverage that in your copy assignment operator. Just take the parameter by value and steal it's resources in the body of the function.

1
2
3
4
5
6
7
8
9
10
11
12
    Stackt<T>& Stackt<T>::operator=(Stackt<T> s)
    {
        delete [] stack;

        MaxSize = s.MaxSize;
        top = s.top;
        stack = s.stack;

        s.stack = nullptr;  // avoid double deletion

        return *this;
    }


Thanks cire for the reply that worked well.
Just one final question. Do this line do the same thing too? i.e copy Source to S

Stackt<int> S (Source);
That line uses the copy constructor, so yes.
Topic archived. No new replies allowed.