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.3. CONSTRUCTORS 69<br />

class complex<br />

{<br />

public:<br />

complex(double rnew, double inew)<br />

{<br />

r= rnew; i= inew;<br />

}<br />

// ...<br />

};<br />

Thus, a constructor is a member function with the same name as the class itself. It can have<br />

an arbitrary number of arguments. In our case, two arguments are most suitable because we<br />

want to set two member variables. This constructor allows us to set c1’s values directly in the<br />

definition:<br />

complex c1(2.0, 3.0);<br />

There is a special syntax <strong>for</strong> setting member variables in constructors<br />

class complex<br />

{<br />

public:<br />

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

// ...<br />

};<br />

This not only shorter but has also another advantage. It calls the constructors of the variables in<br />

class’s constructor. For plain old data types (POD) this does not make a significant difference.<br />

The situation is another one if the members are themselves classes.<br />

Imagine you have a class that solves linear systems with the same matrix and you store the<br />

matrix in your class<br />

class solver<br />

{<br />

public:<br />

solver(int nrows, int ncols) // : A() #1 → error<br />

{<br />

A(nrows, ncols); // this is not a constructor here #2 → error<br />

}<br />

// ...<br />

private:<br />

matrix type A;<br />

};<br />

Suppose our matrix class has a constructor setting the dimensions. This constructor cannot<br />

be called in the function body of the constructor (#2). The call in #2 is interpreted as<br />

A.operator()(nrows, ncols), see § 4.8.<br />

All member variables of the class are constructed be<strong>for</strong>e the class constructor reaches the opening<br />

{. Those members — like A — that do not appear in the list after the colon are built by a constructor<br />

without arguments, called the default constructor. Correspondingly, classes that have<br />

such a constructor are called default-constructible. Our matrix class is not default-constructible<br />

and the compiler will tell us something like “Operator matrix type::matrix type() not<br />

found”. Thus, we need

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

Saved successfully!

Ooh no, something went wrong!