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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

192 CHAPTER 6. INHERITANCE<br />

dbp= static cast(bbp); // erroneous downcast per<strong>for</strong>med<br />

ddp= static cast(bdp); // correct downcast but not checked by the system<br />

std::cout ≪ ”Erroneous downcast of bbp will not return 0, it is: ” ≪ dbp ≪ ’\n’;<br />

std::cout ≪ ”Correct downcast of bdp but not checked at run−time, it is: ” ≪ ddp ≪ ’\n’;<br />

Whether the referred object really allows <strong>for</strong> the downcast cannot be decided at compile time<br />

and lies in the responsibility of the programmer.<br />

Cross-casting<br />

An interesting feature of dynamic cast is casting across from B to C when the referred object’s<br />

type is a derived class of both types:<br />

C∗ cdp= dynamic cast(bdp); // cross−cast from B to C ok: bdp points to an object of type D<br />

std::cout ≪ ”Dynamic cross−cast of bdp should succeed and pointer should not be 0, it is: ” ≪ cdp ≪<br />

’\n’;<br />

Static cross-casting from B to C:<br />

cdp= static cast(bdp); // error: cross−cast from B to C does not compile<br />

is not possible because C is neither a base or derived class of B. It can be casted indirectly over<br />

D:<br />

cdp= static cast(static cast(bdp)); // error: cross−cast from B to C via D<br />

This again is in the responsibility of the programmer whether the addressed object can be really<br />

casted this way.<br />

Comparing Static and Dynamic Cast<br />

Dynamic casting is safer but slower then static casting due the run-time check of the referred<br />

object’s type. Static casting allows <strong>for</strong> casting up and down with the programmer’s responsibility<br />

that the referred objects are handled correctly. Dynamic casting is in some sense always<br />

up, namely from the referred object’s type to a super-type (including itself).<br />

Furthermore, dynamic casting can only be applied on ‘Polymorphic Types’ that are class that<br />

define or inherit a virtual function. The following summarizes the differences between the to<br />

<strong>for</strong>ms of casting:<br />

static cast dynamic cast<br />

Applicability all only polymorphic classes<br />

Cross-casting no yes<br />

Run-time check no yes<br />

Speed no run-time overhead overhead <strong>for</strong> checking<br />

Table 6.1: Static vs. dynamic cast

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

Saved successfully!

Ooh no, something went wrong!