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.7. ACCESSING OBJECT MEMBERS 79<br />

This function works only the complex number is not constant. So we also need a function that<br />

takes a constant reference as argument. In return it can only provide a constant reference of<br />

the number’s real part.<br />

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

This function requires a friend declaration, too.<br />

The functions — in free as well as in member <strong>for</strong>m — can evidently only be called when object<br />

is created. The references of the number’s real part that we use in the statement<br />

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

exist only until the end of the statement. The variable c lives longer. We can create a reference<br />

variable:<br />

double &rr= real(c);<br />

C ++ destroys objects in reverse order. That means that even if rr and c are in the same function<br />

or block, c lives longer than rr.<br />

The same is true <strong>for</strong> constant references if objects from variable declarations are referred.<br />

Temporary objects can also be passed as constant references enabling the definition of outdated<br />

references:<br />

const double &rr= real(complex()); // Bad thing!!!<br />

cout ≪ ”The real part is ” ≪ rr ≪ ’\n’;<br />

The complex variable is created temporarily and only exist until the end of the first statement.<br />

The reference to its real part lives till the end of the surrounding block.<br />

Advise<br />

Do Not Make Constant References Of Temporary Expressions!<br />

They are invalid be<strong>for</strong>e you use them the first time.<br />

3.7.2 Subscript operator<br />

A really stupid way to access vector entries would be writing a function <strong>for</strong> each one:<br />

class vector<br />

{<br />

public:<br />

double& zeroth() { return data[0]; }<br />

double& first() { return data[1]; }<br />

double& second() { return data[2]; }<br />

// ...<br />

int size() const { return my size; }<br />

};

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

Saved successfully!

Ooh no, something went wrong!