Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>dynamic_cast</code> can only cast to a pointer value or reference, which is exactly what the error is telling you.</p> <p>From $5.2.7/1 of the C++ Standard.</p> <blockquote> <p>The result of the expression dynamic_cast&lt; T >(v) is the result of converting the expression v to type T. T shall be a pointer or reference to a complete class type, or “pointer to cv void.”</p> </blockquote> <p>In order for <code>dynamic_cast</code> to throw an exception when the object cannot be converted you need to cast to a reference. Change it to the following:</p> <pre><code>dynamic_cast&lt;AA&amp;&gt;(a).aa(); // ^^^ cast to reference. </code></pre> <p>As <a href="https://stackoverflow.com/a/17129771/845568">Johnsyweb</a> pointed out <code>dynamic_cast</code> will always throw <a href="http://en.cppreference.com/w/cpp/types/bad_cast" rel="nofollow noreferrer"><code>std::bad_cast</code></a> when the conversion fails. Although <code>std::bad_cast</code> is derived from <code>std::exception</code> it is always a good idea to use the exception which best fits the expected fail condition. This prevents inadvertently interpreting other errors as an unsuccessful cast.</p> <p>To apply this to your example it might look like the code below.</p> <pre><code>#include &lt;iostream&gt; #include &lt;typeinfo&gt; // std::bad_cast class A { public: virtual void f(void){} }; class AA:public A { public: void aa(void){}; }; int main(void) { A a; try { dynamic_cast&lt;AA&amp;&gt;(a).aa(); } catch(const std::bad_cast&amp; ex) { std::cout &lt;&lt; "["&lt;&lt;ex.what()&lt;&lt;"]" &lt;&lt; std::endl; } return 0; } </code></pre> <p>[Note, doing things like <code>using namespace std;</code> is strongly discouraged as it can cause conflicts with identifiers in the global namespace. I have removed it in the example above.]</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. 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