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.

214 CHAPTER 7. EFFECTIVE PROGRAMMING: THE POLYMORPHIC WAY<br />

7.5.2 Universal Polymorphism<br />

The universal in the title means, that the different kinds of expression <strong>for</strong> polymorphic behavior<br />

in this section are the most useful techniques to accomplish the desired behavior and should be<br />

used preferably:<br />

• Dynamic polymorphism (subtyping)<br />

• Static polymorphism (parametric)<br />

Subtyping Polymorphism<br />

In <strong>C++</strong> the object-oriented paradigm implements subtyping polymorphism 3 using sub-classing.<br />

The term dynamic polymorphism is often found <strong>for</strong> this type of polymorphism.<br />

To introduce the applicability of this kind of polymorphism an example from the topological<br />

area is given. Classes <strong>for</strong> different kinds of points are used, which should be comparable in their<br />

own set. Traversing through containers or data structures is a quite common task in generic<br />

programming. The next code snippet presents the base class <strong>for</strong> all kind of vertices.<br />

#include<br />

class topology { };<br />

class vertex<br />

{<br />

public:<br />

virtual bool equal(const vertex∗ ve) const = 0;<br />

};<br />

If these vertex types have to be extended, only the new class with the according equal method<br />

should be implemented. The next code snippet presents two possible implementations <strong>for</strong> a<br />

vertex, which can be used in different topologies.<br />

class structured vertex : public vertex<br />

{<br />

public:<br />

structured vertex(int id, topology∗ topo) : id(id), topo(topo) {}<br />

virtual bool equal(const vertex∗ ve) const<br />

{<br />

const structured vertex∗ sv = dynamic cast(ve);<br />

return ((id == sv→ id) && (topo == sv→ topo));<br />

}<br />

protected:<br />

int id;<br />

topology∗ topo;<br />

};<br />

3 Also called inclusion polymorphism.

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

Saved successfully!

Ooh no, something went wrong!