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.

78 CHAPTER 3. CLASSES<br />

This mechanism applies recursively. For instance, if type1 is itself a class with an automatically<br />

generated default constructor the default constructors of its members are called in the order<br />

of their definition. Of those variables or some of them are also classes then their default<br />

constructors are called and so <strong>for</strong>th. If the type of a member variable is an intrinsic type like int<br />

or float then there are evidently no such operators because the types are no classes. However,<br />

the behavior can be easily emulated: the “default constructor” just creates it with a random<br />

value (whatever bits where set on the according memory position be<strong>for</strong>e determine its value),<br />

the “copy constructor” and the “copy assignment” copy the values and the “destructor” does<br />

nothing.<br />

3.7 Accessing object members<br />

3.7.1 Access functions<br />

In § 3.2.2 we introduced getters and setters to access the variables of the class complex. This<br />

becomes cumbersome when we want <strong>for</strong> instance increment the real part:<br />

c.set r(c.get r() + 5.);<br />

This does not really look like numeric operations and is not very readable either. A better way<br />

dealing with this is writing a member function that returns a reference:<br />

class complex { public:<br />

double& real() { return r; }<br />

};<br />

With this function we can write:<br />

c.real()+= 5.;<br />

This looks already much better but still a little bit weird. Why not incrementing like this:<br />

real(c)+= 5.;<br />

To do this, we write a free function:<br />

inline double& real(complex& c) { return c.r; }<br />

But this function access the private member ‘r’. We can modify the free function calling the<br />

member function:<br />

inline double& real(complex& c) { return c.real(); }<br />

Or alternatively declaring the free function as friend of complex:<br />

class complex { public:<br />

friend double& real(complex& c);<br />

};<br />

Functions or classes that are friends can access private and protected data. A strange issue<br />

with this free function is that the inline attribute must be written be<strong>for</strong>e the reference type.<br />

Usually it does not matter whether the inline is written be<strong>for</strong>e or after the return type. 9<br />

9 TODO: Anybody a decent explanation <strong>for</strong> this?

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

Saved successfully!

Ooh no, something went wrong!