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.

194 CHAPTER 6. INHERITANCE<br />

Our compilers are so sophisticated, they certainly handle de Morgan’s law perfectly. Negating<br />

the equality operator is something we can do on every type that has an equality operator. We<br />

could copy-and-past this code snippet and just replace the type of the argument.<br />

Alternatively, we can write a class like this:<br />

template <br />

struct unequality<br />

{<br />

bool operator!=(const T& that) const { return !(static cast(∗this) == that); }<br />

};<br />

and derive from it:<br />

class point : public unequality { ... };<br />

This mutual dependency:<br />

• One class is derived from the other and<br />

• The latter takes the derived class’ type as template argument<br />

is somewhat confusing at the first view.<br />

Essential <strong>for</strong> this to work is that the code of a template class member is only generated when<br />

the class is instantiated and the function is actually called. At the time the template class<br />

‘unequality is parsed, the compiler checks only the correctness of the syntax.<br />

When we write<br />

int main (int argc, char∗ argv[])<br />

{<br />

point p1(3, 4), p2(3, 5);<br />

std::cout ≪ ”p1 != p2 is ” ≪ (p1 != p2 ? ”true” : ”false”) ≪ ’\n’;<br />

}<br />

return 0 ;<br />

fter the definition of unequality and point both types are completely known to the compiler.<br />

What happens when we call p1 != p2?<br />

1. The compiler searches <strong>for</strong> operator!= in class point → without success.<br />

2. The compiler looks <strong>for</strong> operator!= in the base class unequality → with success.<br />

3. The this pointer of unequality refers a component of point’s this pointer.<br />

4. Both types are completely known and we can statically down-cast the this pointer to point.<br />

5. Since we know that the this pointer of unequality is an up-casted this pointer to<br />

point 3 we are save to down-cast it to its original type.<br />

6. The equality operator <strong>for</strong> point is called. Its implementation is already known at this point<br />

because the code of unequality’s operator!= is not generated be<strong>for</strong>e the instantiation<br />

of point.<br />

3 Unless the first argument is really of type unequality. There are also ways to impede this, e.g. http:<br />

//en.wikipedia.org/wiki/Barton-Nackman_trick but we used this unary operator notation <strong>for</strong> the sake of<br />

simplicity.

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

Saved successfully!

Ooh no, something went wrong!