Question

I Know how to write the code , but can't explain the meaning of the code here:

 ArrayList& ArrayList::operator =(const ArrayList& other) {
          delete[] m_elements;
          copy(other);
          return *this; 
 }

1st Question

I know ArrayList& means "pass it by reference". But this is the first time for me to see ArrayList& as return type of a method. What is the difference between:

ArrayList ArrayList :: operator() {} 

and

ArrayList& ArrayList :: operator(){}

2nd Question

Whats does return *this mean? Why return the pointer? Shouldn't it be return this;?

** EDITED

3rd QUestion

Does the code below mean "This method Return some strange memory address (something like 0x90183930)" by Reference" ?

             ArrayList*& ArrayList ::operator(){}
Was it helpful?

Solution 2

The standard assignment operator semantics return the assigned value as a result of the assignment.

So really it should return either an ArrayList or a const ArrayList&. The later is preferred with large objects, since it only passes around an address, not a full copy of the value in question.

btw, its returning *this, since after having completed the assignment, *this is the value that was assigned.

OTHER TIPS

A datatype followed by an ampersand in C++ is simply a reference to the object, instead of the object as a whole (which would be a copy). Hence ArrayList& is a reference to an object of type ArrayList.

The second question follows from this. In the context of class ArrayList, this is a pointer to the current instance, thus of type ArrayList*. The * before this dereferences this pointer, resulting in the object being pointed to, which is valid to be passed by reference, and as such conforms to the specified return type of ArrayList&.

If it returned this instead of *this the return type would've had to be ArrayList*.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top