Dynamic array keeps crashing my program

Hi, I'm following the code from http://www.cplusplus.com/doc/tutorial/dynamic/ (at the bottom under the "Operators delete and delete[]) to try and make a dynamic array but I'm trying to do it in an object oriented way for school.

I have my specification and implementation file and my main program. The problem is the program always crashes when it goes to output the array and I cant figure out why. The program works fine like in the tutorial if I have it all in main but not when I separate it. Can anyone see what I'm doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//specification file

class Numbers
{
public:
	void inputSize();
	void inputNum();
	void outputNum();
	void deleteArray();

	int size = 0;
	int *ptr = new int[size];

private:
};


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
//implementation file

#include "num.hpp"
#include <iostream>

using namespace std;

void Numbers::inputSize()
{
	cout << "How many numbers would you like to type? ";
	cin >> size;
}

void Numbers::inputNum()
{
	for (int i = 0; i < size; i++)
	{
		cout << "Enter number: ";
		cin >> ptr[i];
	}
}


void Numbers::outputNum()
{
	for (int i = 0; i < size; i++)
		cout << ptr[i] << ", ";
}

void Numbers::deleteArray()
{
	delete[] ptr;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "num.hpp"
#include <iostream>

using namespace std;

int main()
{
	Numbers testNum;

	testNum.inputSize();
	testNum.inputNum();
	testNum.outputNum();
	testNum.deleteArray();

	return 0;
}
Last edited on
I would start off by rewriting your class like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Numbers
{
public:
    Numbers(int size) : size(size) {

      ptr  = new int[size];

    }

    virtual ~Numbers() { delete[] ptr}
    

private:

    int size = 0;
    int *ptr;


};


Then that class should prompt you to rework your implementation.
Thanks for your reply, I'm not really familiar with the virtual keyword and I haven't really started using destructors yet. I was hoping more to find the problem with the code that I wrote and try and fix that. Is there anything in my code that could be causing my program to crash?
Topic archived. No new replies allowed.