Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'll forget that <code>array[0] = A item1;</code> isn't valid C++ and just assume that you're assigning an object of type <code>A</code> to <code>array[0]</code> and an object of type <code>B</code> to <code>array[1]</code>. Okay, so you have two problems.</p> <p>The first is known as object slicing. When you copy an object of type <code>B</code> to an object of type <code>A</code>, you only copy the <code>A</code> part of that object. So what you have in <code>array[1]</code> is not a <code>B</code> at all, it's just an <code>A</code>. If you want polymorphism (which you do), then you need to use either pointers or references which provide polymorphic behaviour. That means make your array an <code>A* array[2];</code> and do <code>array[0] = &amp;item1; array[1] = &amp;item2;</code>.</p> <p>Now, when you call a function on a pointer to <code>A</code> that points to a <code>B</code> it will still only call <code>A</code>s <code>foo</code> member function. Why? Because by default, the function will be looked up on the <em>static type</em> of the object. That static type is <code>A</code>. If you want to tell the compiler to look up your function on the <em>dynamic type</em> of your object - the <em>true</em> type of your object, which is <code>B</code> - you need to make that member function virtual. So in <code>A</code>, do:</p> <pre><code>virtual int foo(int c) { c = c+1; return c; }; </code></pre> <p>Now when your compiler see that you're calling <code>foo</code> on an <code>A*</code>, it'll see that it's virtual and say "Oh okay, I should look up this function dynamically" and it'll find <code>B</code>'s implementation of <code>foo</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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