Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's allowed because of <code>is-a</code> relationship.</p> <p>When you <em>publicly</em><sup>1</sup> derive <code>Derived</code> from <code>Base</code>, you're annoucing to the compiler that <code>Derived</code> <strong>is a</strong> <code>Base</code>. Hence it should be allowed to do this:</p> <pre><code>Base base = derived; </code></pre> <p>and then use <code>base</code> as it is. that is:</p> <pre><code>base.message(); //calls Base::message(); </code></pre> <p>Read this:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Is-a" rel="nofollow">Is-A Relationship</a></li> </ul> <p><sup>1. If you <em>privately</em> derive <code>Derived</code> from <code>Base</code>, then it is <code>has-a</code> relationship. That is sort of composition. Read <a href="http://www.parashift.com/c++-faq-lite/private-inheritance.html" rel="nofollow">this</a> and <a href="http://en.wikipedia.org/wiki/Has-a" rel="nofollow">this</a>. </sup></p> <p>However, in your case, if you don't want slicing, then you can do this:</p> <pre><code>Base &amp; base = derived; base.message(); //calls Derived::message(); </code></pre> <hr> <p>From your comment : </p> <blockquote> <p>Wouldn't it better for C++ to prevent object slicing while only allow the pointer/reference to work for is-a relationshp ??? </p> </blockquote> <p>No. Pointer and Reference doesn't maintain <code>is-a</code> relationship if the base has virtual function(s). </p> <pre><code> Base *pBase = &amp;derived; pBase-&gt;message(); //doesn't call Base::message(). //that indicates, pBase is not a pointer to object of Base type. </code></pre> <p>When you want one object of one type to behave like an object of it's base type, then that is called <code>is-a</code> relationship. If you use pointer or reference of base type, then it will not call the <code>Base::message()</code>, which indicates, pointer or reference doesn't have like a pointer or reference to an object of <em>base</em> type.</p>
    singulars
    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