Returning classes from operator+ ... error

I have built a class to handle char pointer arrays.

The code errors on the return from the operator+.

It is executing the deconstructor of temp before leaving the routine (because it was created within the routine). The problem is, it is this class I am supposed to be returning. The code with the a+b bit, then errors because the memory has been removed from underneath it.

So...
1) It this an a appropriate use of the deconstructor?
2) How can I return a class from an operator method if the object is unloaded from memory before it is returned?
3) If 2 is "you cant", then does that mean I can't use operators with classes???

Please don't just suggest using cstring... this is a way of learning about c++, nothing more.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Txt {

public:
	unsigned int length;
	char* text;

	Txt();

	Txt(char* t);

	~Txt();

	Txt operator+ (const char* t) const;

};


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
#include "m.Txt.h"

Txt::Txt() {
};

Txt::Txt(char* t) {
	length = stringlength(t);
	text = new char[length + 1];
	for (unsigned int i = 0; i <= length; i++) {
		text[i] = t[i];
	};
};

Txt::~Txt() {
	delete[] text;
};

Txt Txt::operator+ (const char* t) const
{
	unsigned int tlen = stringlength(t);

	Txt temp;
	temp.length = this->length + tlen;
	temp.text = new char[temp.length + 1];

	for (unsigned int i = 0; i < this->length; i++) {
		temp.text[i] = this->text[i];
	};

	for (unsigned int i = 0; i <= tlen; i++) {
		temp.text[i + this->length] = t[i];
	};

	return temp;
};


Thanks!
Last edited on
If you need a destructor, a copy constructor or an assignment operator, you need the three.

Also, I recommend to create the arithmetic operators in base to the compound assignment.
1
2
3
4
5
6
7
8
9
Txt& Txt::operator +=(const Txt &b){
   //...
}

Txt operator+(const Txt &a, const Txt &b){
   Txt result(a);
   result += b;
   return result;
}
Topic archived. No new replies allowed.