03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.5. ASSIGNMENT 75<br />

It must be paid attention that the freed ressources are not used or released somewhere else in<br />

the program afterwards. C ++ generates a default destructor in the same way as the default<br />

constructor: calling the destructor of each member but in the reverse order. 6<br />

3.5 Assignment<br />

Assignment operators are used to enable <strong>for</strong> user-defined types expressions like:<br />

x= y;<br />

u= v= w= x;<br />

As usual we consider first the class complex. Assigning a complex to a complex requires an<br />

operator like:<br />

complex& operator=(const complex& src)<br />

{<br />

r= src.r; i= src.i;<br />

return ∗this;<br />

}<br />

Evidently, we copy the members ‘r’ and ‘i’. The operator returns a reference to the object<br />

<strong>for</strong> enabling multiple assignments. ‘this’ is a pointer to the object itself and since we need a<br />

reference <strong>for</strong> syntactic reasons it is dereferred. What happens if we assign a double?<br />

c= 7.5;<br />

It compiles without the definition of an assignment operator <strong>for</strong> double. Once again, we have a<br />

implicit conversion: the implicit constructor creates a complex on the fly and assigns this one.<br />

If this becomes a per<strong>for</strong>mance issue we can add an assignment <strong>for</strong> double:<br />

complex& operator=(double nr)<br />

{<br />

r= nr; i= 0;<br />

return ∗this;<br />

}<br />

An assignment operator like the first one that assigns a an object of the same type is called<br />

Copy Assignment and this operator is synthesized by the compiler. In the case of complex<br />

numbers the generated copy assignment operator per<strong>for</strong>ms exactly what we need, copying all<br />

members.<br />

As <strong>for</strong> the vector the synthesized operator is not satisfying because it only copies the address<br />

of the data and not the data itself. The implementation is very similar to the copy constructor:<br />

vector& operator=(const vector& src)<br />

{<br />

if (this == &src)<br />

return ∗this;<br />

assert(my size == src.my size);<br />

<strong>for</strong> (int i= 0; i < my size; i++)<br />

data[i]= src.data[i];<br />

6 TODO: Good and short explanation why. If possible with example.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!