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.

190 CHAPTER 6. INHERITANCE<br />

6.4.1 Casting Between Base and Derived Classes<br />

Casting Up<br />

⇒ up down cast example.cpp<br />

Casting up, i.e. from a derived to a base class, is always possible if there are no ambiguities and<br />

can be even per<strong>for</strong>med implicitly. Assume we have the following class structure: 1<br />

struct A<br />

{<br />

virtual void f(){}<br />

virtual ∼A(){}<br />

int ma;<br />

};<br />

struct B : A { float mb; };<br />

struct C : A {};<br />

struct D : B, C {};<br />

and the following unary functions:<br />

void f(A a) { /∗ ... ∗/ }<br />

void g(A& a) { /∗ ... ∗/ }<br />

void h(A∗ a) { /∗ ... ∗/ }<br />

An object of type B can be passed to all three funtions:<br />

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

{<br />

B b;<br />

f(b);<br />

g(b);<br />

h(&b);<br />

}<br />

return 0 ;<br />

In all three cases the object b is implicitly converted to an object of type A. The call of function<br />

‘f’ is however a bit different: only b’s members within class A are copied into the function<br />

argument and the remainder — in our example the member ‘mb’ is not accessible in f by any<br />

means. The functions ‘g’ and ‘h’ refer to an object of type A by reference or pointer. If an<br />

object of a derived class is passed to one of those functions the other members are in principle<br />

still there but just hidden. One could still access them by down-casting the argument in the<br />

function. Be<strong>for</strong>e we down-cast we should ask ourselves the following questions:<br />

• How do we assure that the argument passed to function is really an object of the derived<br />

class? For instance with extra arguments or with run-time tests.<br />

• What can we do if the object cannot be down-casted?<br />

• Can we write directly a function <strong>for</strong> the derived class?<br />

• Why we do not overload the function <strong>for</strong> the base and the derived type? This is definitively<br />

a much cleaner design and always feasible.<br />

1 TODO: picture

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

Saved successfully!

Ooh no, something went wrong!