Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Consider</p> <pre><code>class Base {}; class Derived : public Base {}; template&lt;typename T&gt; class TemplateClass {}; </code></pre> <p>Contrary to what you might think, <code>TemplateClass&lt;Derived&gt;</code> <em>is not a</em> <code>TemplateClass&lt;Base&gt;</code> in the sence of inheritance, so pointers to the former can't be implicitly converted to pointers of the later.</p> <p>So why does explicitly casting a pointer to <code>TemplateClass&lt;Derived&gt;</code> to a pointer of <code>TemplateClass&lt;Base&gt;</code> compile? Because any pointer of a certain type may be explicitly cast to any pointer of any other type, however <strong>there are no guarantees the conversion is valid</strong>! You could for instance just as well write</p> <pre><code>int* i = (int*) new TemplateClass&lt;Derived&gt;; </code></pre> <p>and it would compile just fine, even though it is clearly an invalid conversion.</p> <p>Now why does your example work? Sheer luck. At the point a pointer containing an address obtained through an invalid pointer cast gets dereferenced, the program becomes invalid and its bahavior undefined. Anything can happen, including doing what you would expect.</p> <p>If you want <code>TemplateClass&lt;Derived&gt;</code> <em>to be a</em> <code>TemplateClass&lt;Base&gt;</code> in the sence of inheritance, you can define an specialization of <code>TemplateClass&lt;&gt;</code> stating this relationship explicitly, like the following:</p> <pre><code>template&lt;&gt; class TemplateClass&lt;Derived&gt; : public TemplateClass&lt;Base&gt; {}; </code></pre>
    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. 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