Returning a new object

The purpose of the below function is to copy the information of the caller, and the information of the object on the Right Hand Side. Then return a combination of the two, without repeats. (Set Union)

I believe my code is working as far as copying the two Set objects, but when I return I'm returning a temporary address that once the function has completed running, goes out of scope. Which in turn causes my = operator to fail.

Is there a way to get around this?

As a part of this assignment I am not allowed to modify S1 (the caller) or S2 (the object being called).

I've overloaded the = operator, as well as the << operator. I've tested those and they work for sure.

Call inside the Main.cpp
1
2
3
//Store the results of S1 + S2 inside S3
S3 = S1+S2;
cout << S3;


Implementation in the Set.cpp file
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
  Set & Set::operator+(Set &obj){
	Set newList;
	ListNode *newNode;
	ListNode *nLhere = newList.head->next;
	ListNode *nLprev = newList.head;

	ListNode *objhere = obj.head->next;
	ListNode *objprev = obj.head;

	ListNode *here = this->head->next;
	ListNode *prev = this->head;

	//Copy Elements of List 1 into newList;
	while (here->next != NULL){
		newNode = new ListNode(here->integer);
		nLprev->next = newNode;
		newNode->next = nLhere;

		prev = here;
		here = here->next;

		nLprev = nLprev->next;
		nLhere = newNode->next;
	}

	//Copy Elements of List 2 into newList;
	while (objhere->next != NULL){
		if (!newList.find(objhere->integer))
		{
			newList.Insert(objhere->integer);
		}

		objprev = objhere;
		objhere = objhere->next;
	}

        //Returning a temporary variable, bad idea, need a new one
	return newList;
}


Thanks for taking a look!
Remove the first, but not the second, ampersand on line 1. Prior to C++11, copy-elision is a common compiler optimization. After C++11, move semantics will take care of it for you.

By the way, the parameter and the function itself should be const.
Last edited on
Problem solved. Thank you.
Topic archived. No new replies allowed.