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.

70 CHAPTER 3. CLASSES<br />

class solver<br />

{<br />

public:<br />

solver(int nrows, int ncols) : A(nrows, ncols) {}<br />

// ...<br />

private:<br />

matrix type A;<br />

};<br />

Often the matrix (or whatever other object) is already constructed and we do not like to waste<br />

the memory <strong>for</strong> a copy. In this case we will use a reference to the object. A reference must<br />

be set in the constructor because this is the only place to declare what it is referring to. The<br />

solver shall not modify the matrix, so we write:<br />

class solver<br />

{<br />

public:<br />

solver(const matrix type& A) : A(A) {}<br />

// ...<br />

private:<br />

const matrix type& A;<br />

};<br />

The code also shows that we can give the constructor arguments the same names as the member<br />

variables. After the colon, which A is which? The rule is that names outside the parenthesis<br />

refer to members and inside the parenthesis the constructor arguments are hiding the member<br />

variables. Some people are confused by this rule and use different names. To what refers A<br />

inside {}? To the constructor argument. Only names that does not exist as argument names<br />

are interpreted as member variables. In fact, this is a pure scope resolution: the scope of the<br />

function — in this case the constructor — is inside the scope of the class and thus the argument<br />

names hide the class member names.<br />

Let us return to our complex example. So far, we have a constructor allowing us to set the real<br />

and the imaginary part. Often only the real part is set and the imaginary is defaulted to 0.<br />

class complex<br />

{<br />

public:<br />

complex(double r, double i) : r(r), i(i) {}<br />

complex(double r) : r(rnew), i(0) {}<br />

// ...<br />

};<br />

We can also say that the number is 0 + 0i if no value is given, i.e. if the complex number is<br />

default-constructed:<br />

complex() : r(0), i(0) {}

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

Saved successfully!

Ooh no, something went wrong!