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.

7.5. FROM MONOMORPHIC TO POLYMORPHIC BEHAVIOR 215<br />

class unstructured vertex : public vertex<br />

{<br />

public:<br />

unstructured vertex(int handle, topology∗ topo, int segment) : handle(handle), segment(segment), topo(topo) {}<br />

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

{<br />

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

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

}<br />

protected:<br />

int handle;<br />

int segment;<br />

topology∗ topo;<br />

};<br />

With this virtual class hierarchy, an algorithm which operates on all different classes derived<br />

from vertex can be written. This is called explicit interface.<br />

void print equal(const vertex∗ ve1, const vertex∗ ve2)<br />

{<br />

std::cout ≪ std::boolalpha ≪ ve1→ equal(ve2) ≪ std::endl;<br />

}<br />

The next code lines present the generic behavior of the algorithm, which operators on both<br />

types derived from vertex.<br />

int main()<br />

{<br />

topology the topo;<br />

vertex∗ the vertex1;<br />

vertex∗ the vertex2;<br />

}<br />

// ∗∗∗ structured<br />

the vertex1 = new structured vertex(12, &the topo);<br />

the vertex2 = new structured vertex(12, &the topo);<br />

print equal(the vertex1, the vertex2);<br />

// ∗∗∗ unstructured<br />

the vertex1 = new unstructured vertex(12, &the topo, 1);<br />

the vertex2 = new unstructured vertex(12, &the topo, 2);<br />

print equal(the vertex1, the vertex2);<br />

return 0;<br />

As can be seen, polymorphic behavior can be achieved, but with major drawbacks. First,

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

Saved successfully!

Ooh no, something went wrong!