Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First: you're mixing two concepts: polymorphism, and value vs. reference semantics.</p> <h2>Runtime polymorphism</h2> <p>Polymorphism comes in many shapes. Depending on the runtime you use, other options are available. </p> <p>An interpreted language (like Ruby, Python, Javascript, ...) allows for 'duck typing': if an object merely <em>has</em> a method called <code>foo</code>, you can call it. Typically these languages do garbage collection, so the notion of pointers vs. objects isn't too relevant.</p> <p>C++ has a different viewpoint: polymorphism is allowed, but in a more strict way. Enforcing a common base class (which may be abstract) allows the compiler to check the semantics of your code: this way the compiler assures that you really meant the <code>foo</code> method which implements the intended interface, and not some mishmash of <code>foo</code>s.</p> <p>This polymorphism is realized through the use of a <code>virtual</code> function: a pointer to a function, which may vary amongst implementations. The caller of <code>foo</code> will first have to look up the value of the function pointer, and then jump to that function.</p> <p>So far for polymorphism.</p> <h2>Containment</h2> <p>Now for containment: if you create an array of <code>line</code> objects in C++, these objects are right next to each other in memory; they're contained <em>by value</em>. When you pass the array to a function, the called function can only receive an array of the same type. Otherwise, taking a step of <code>sizeof(shape)</code> into the array we would end up in the mid of a <code>line</code>.</p> <p>In order to fix that, you can contain the objects 'by reference' - in C++ we use pointers for that.</p> <h2>Compile-time polymorphism</h2> <p>But there is another way to achieve polymorphic functions: templates. You <em>can</em> write your <code>drawshapes</code> function with a template argument that says which type of object you are using:</p> <pre><code>template&lt; typename tShape, size_t N &gt; void drawshapes( tShape (&amp;aShapes)[N] ) { for( tShape* shape=aShapes; shape != aShapes+N; ++shape ) { shape-&gt;draw(); } } </code></pre> <p>(Note: there are stl functions to simplify this, but that's out of the scope of the question.</p> <pre><code>std::for_each( shapes, shapes+10, mem_fun_ref( &amp;shape::draw ) ); </code></pre> <p>)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload