c++ How to dynamically increase the size of an array within a overload function of a class ?

I'm having a lot of troubles with this. I'm trying to overload ++(postfix)
to increase the size of a dynamic array. I make a new dynamic array with the original size plus one. Then I copy all the attributes from the old dynamic array into the new one. Then I delete the old array and have the pointer point to the new array. Finally I have the person fill in the new spot. This is giving me troubles and causing crashes. I know it has something to do with the way I'm deallocating memory i just don't know what exactly. Also note there's a destructor that's also deallocating the array. But I don't understand why this is a problem if the pointer is still pointing to a dynamic array.

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
88
89
90
91
92
93
94

template <class T>
class SimpleVector
{
private:
	T *aptr;
	int arraySize;
	void memError();
	void subError();

public:

	//Constructors
	SimpleVector();
	SimpleVector(int);
	SimpleVector(const SimpleVector &);

	//Destructor
	~SimpleVector();

	//Modifiers
	int size() const;

	T getElementAt(int);
	void sortArray();

	//Operators overloading
	SimpleVector<T> operator ++ (int);

	T & operator[](const int &);
};
	
template <class T>
SimpleVector<T>::SimpleVector()
{
	aptr = 0; arraySize = 0;
}

template <class T>
SimpleVector<T>::SimpleVector(int s)
{
	arraySize = s;

	try
	{
		aptr = new T[s];
	}
	catch (bad_alloc)
	{
		memError();
	}

	for (int count = 0; count < arraySize; count++)
		* (aptr + count) = 0;
}

template <class T>
SimpleVector<T>::SimpleVector(const SimpleVector & obj)
{
	arraySize = obj.arraySize;
	aptr = new T[arraySize];

	if (aptr == 0)
		memError();

	for (int count = 0; count < arraySize; count++)
		* (aptr + count) = *(obj.aptr + count);
}

template <class T>
SimpleVector<T>::~SimpleVector()
{
	if (arraySize > 0)
		delete[] aptr;
}

template <class T>
SimpleVector<T> SimpleVector<T>::operator ++ (int)
{
	
	arraySize = size() + 1;
	T * tempArray = new T(arraySize);
	for (int count = 0; count < size(); count++)
	{
		tempArray[count] = aptr[count];
	}
	delete[] aptr; 
	aptr = tempArray;
	cin >> aptr[arraySize-1];

	return (*this); 

}
The problem is on line 82:

1
2
T * tempArray = new T(arraySize); // Note: a single object initialized with arraySize  is created
// -> use [] instead of () 


I suggest that you don't return a copy of the object. Better a reference (use &) or void is also possible.
Thank you! That helped.
Topic archived. No new replies allowed.