redundant if statement in my function

Hi guys,

I am currently creating a copy constructor and an overloaded = operator for my linkedList class. I was following a tutorial to help me with the overloaded = function and I am pretty sure the if statement below is redundant i.e. the whole function + the while loop inside will work the exact same without the if statement.

Can someone correct me if i am wrong please and let me know if there is any use for this if statement.

Cheers

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
const ListOfEmployee& ListOfEmployee::operator= (const ListOfEmployee& rhs)
{
	if (this != &rhs)//check for self assignemnt
	{
		// free memory of lhs 

		//if(head != NULL)            ***THIS IF STATEMENT
		//{
			while (head != NULL)    
			{
				deleteMostRecent();
			}
		//}

			ListPtr copyPtr = NULL;
			ListPtr origPtr = rhs.head;

			while (origPtr != NULL) //loop through rhs setting data to lhs
			{
				if (head == NULL) 
				{
					//points head and copyPtr to newly created node
					head = copyPtr = new EmployeeListNode(origPtr->emp.name, origPtr->emp.salary);
				}
				else
				{
                                        //sets copyPtr->next to newely created node
					copyPtr->next = new EmployeeListNode(origPtr->emp.name, origPtr->emp.salary);
					copyPtr = copyPtr->next;//sets copyPtr to our new node
				}
				origPtr = origPtr->next;//moves origPtr along until its NULL which ends while loop
			}
	}

	return *this;
}
Last edited on
Yes, the if-statement is redundant, since the while loop checks the exact same thing.

Note that if we include the if-statement, your indentation is misleading starting on line 15. Just something to be aware of.
Last edited on
Thanks buddy.
Topic archived. No new replies allowed.