Initialising an Array

Hi there. I'm a first time poster....

I'm getting to grips with C++ after 3 years coding in managed languages such as C# and Java. Being a cpp novice, I decided that the best move to acquaint myself with the language would be to make a number of data structures... but i'm falling at the first hurdle when attempting to compile my stack. I was wondering if anyone could help me here.

I am getting error C2229
Stack<Object> has an illegal zero-sized array.

I'm declaring my array within the header file, but I don't wish to initialise it until the stacks constructor where the Stacks size can be declared. Am I doing something wrong? Thanks in advance for any help you could give.

PS :

Oh yeah, I find it odd that I need to place 'template <class Object>' prior to every function containing 'Object'. Am i using that line correctly?

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Code within the header file ('Stack.h')
template <class Object>
class Stack
{
public:
	Stack(int STACKSIZE);
	~Stack(void);

	void Push(Object Object);
	Object Pop();
	void Clear();
	bool isFull();
	bool isEmpty();

private:
	Object _obj;
    Object* _dataArr[];
	string _strExc;
	int _size;
	int _top;

};

//Code within the .cpp file
#include "Stack.h"
#include <stdexcept>
#include <iostream>
#include <sstream>

using namespace std;

	template <class Object>
	Stack<Object>::Stack(int STACKSIZE)
	{
		_size = STACKSIZE;
		_dataArr = new Object[_size];
		_top = 0;
		_obj = 0;
	};
	template <class Object>
	Stack<Object>::~Stack()
	{
		delete _dataArr;
	};
	template <class Object>
	void Stack<Object>::Push(Object Input)
	{
		_obj = &Input;
		
		cout << "Pushing Value : " << _obj << endl;

		if (!isFull())
		{
			_dataArr[_top] = _obj;
			_top ++;
			cout << "Stack holds " << _size-_top << "spaces left.";
			return;
		}
		_strExc =  "Stack Overflow : Current index ("+ to_string( _top) + ") exceeds stack size ("+to_string(_size) +")";
		throw std::invalid_argument(_strExc);
	};
	template <class Object>
	Object Stack<Object>::Pop()
	{
		_obj = 0;

		if (_dataArr[_top] != 0)
		{
			_obj = _dataArr[_top];
			_top --;
			cout << "Stack holds " << _size-_top << "spaces left.";
		}
		
		cout << "Popping Value : " << _obj << endl;

		return _obj;
	}
	template <class Object>
	bool Stack<Object>::isEmpty()
	{
		return (_top <= 0);
	}
	template <class Object>
	bool Stack<Object>::isFull()
	{
		return (_top >= _size);
	}
Last edited on


remove the [] on line 17, it should read

Object* _dataArr;

Oh bloody hell....

Thank you so much! I knew it would have been something stupid.

:)

Your welcome.
Topic archived. No new replies allowed.