Returning a local instance out of scope, help!

closed account (N1A5SL3A)
I am currently writing a custom string class that uses cstring to store the data. On top of that, I am writing operator overloads. Here is what I'm trying to perform:

jumboStr = (jumboStr + temp); //Combines strings: "bat" + "man" = "batman"

I believe my assignment function is correct, but in my + operator function, I am trying to return a dead instance. I'm stuck and would GREATLY appreciate some help. Thanks.

Here are my constructor, =, and + functions.

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
  CDString::CDString(char * ptr)
{
	cap = 20;
	end = 0;
	str = new char[cap];
	str[0] = '\0';
	while (str[end] = ptr[end])
		end++;
	createdCount++;
}

void CDString::operator = (const CDString& rValue)
{
	delete[] str;
	int x = rValue.cap;
	str = new char[x];
	cap = x;
	for (int i = 0; i <= rValue.end; i++)
		str[i] = rValue.str[i];
	end = rValue.end;
}

CDString& CDString::operator + (const CDString& rVal) const
{
	CDString tempStr;
	tempStr.end = end + rVal.end;

	tempStr.cap = cap + rVal.cap;
	//if ((tempStr.cap % end) >= 20)
	//	tempStr.cap = tempStr.cap - 20;

	delete[] tempStr.str;
	tempStr.str = new char[tempStr.cap];

	for (int x = 0; x < end+1; x++)
		tempStr.str[x] = str[x];

	int num1 = 0;
	for (int x = end; x < rVal.end; x++)
	{
		tempStr.str[x] = rVal.str[num1];
		num1++;
	}	

	return tempStr;
}
Topic archived. No new replies allowed.