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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

76 CHAPTER 3. CLASSES<br />

}<br />

return ∗this;<br />

In fact every class implementation where the copy assignment and the copy constructor have<br />

essential differences in their implementation are very confusing in their behavior and should not<br />

be used, cf. [SA05, p. 94]. The two operations differ in the respect that a constructor creates<br />

content in a new object while an assignment replaces content in an existing object. However,<br />

both the creation as well as the replacement is per<strong>for</strong>med with a copy semantics and the two<br />

operations should behave consistently there<strong>for</strong>e.<br />

An assignment of an object to itself (source and target have the same address) can be skipped,<br />

line 3 and 4. In line 5 it is tested whether the assignment is a legal operation by checking<br />

the equality of their size. Alternatively the assignment could resize the target if the sizes are<br />

different but that does not correspond to the authors’ understanding of vector behavior — or<br />

can you think of a context in mathematics or physics where a vector space all of a sudden<br />

changes its dimension.<br />

3.6 Automatically Generated Operators<br />

If you define a class without operators C ++ will generate the following four:<br />

• Default constructor;<br />

• Copy constructor;<br />

• Destructor; and<br />

• Copy assignment.<br />

Assume you have a class without any function but with some member variables like this:<br />

class my class<br />

{<br />

type1 var1;<br />

type2 var2;<br />

// ...<br />

typen varn;<br />

};<br />

Then the compiler adds the four operators and your class behaves as you would have written:<br />

class my class<br />

{<br />

public:<br />

my class()<br />

: var1(),<br />

var2(),<br />

// ...<br />

varn()<br />

{}<br />

my class(const my class& that)<br />

: var1(that.var1),<br />

var2(that.var2),

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

Saved successfully!

Ooh no, something went wrong!