Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <ol> <li><code>NULL-&gt;derivedspecific()</code> won't compile</li> <li><code>((derived*)NULL)-&gt;derivedspecific()</code> is undefined behaviour (segmentation fault on most platforms</li> </ol> <p>there is a mechanism which is specifically designed to support this kind of behaviour, i.e. <code>dynamic_cast</code> which goes like:</p> <pre><code>#include &lt;typeinfo&gt; class base { public: virtual ~base(){}; }; class derived1 : public base { public: void derived1specific() const {} }; class derived2 : public base { public: void derived2specific() const {} }; int main() { // use pointers base* test = new derived1; derived2* d2 = dynamic_cast&lt;derived2*&gt;(test); if(d2) d2-&gt;derived2specific(); derived1* d1 = dynamic_cast&lt;derived1*&gt;(test); if(d1) d1-&gt;derived1specific(); // or simply if(derived1* d1 = dynamic_cast&lt;derived1*&gt;(test) ) d1-&gt;derived1specific(); else if(derived2* d2 = dynamic_cast&lt;derived2*&gt;(test)) d2-&gt;derived2specific(); // use references const base&amp; testr = derived1(); try{ const derived1&amp; d1 = dynamic_cast&lt;const derived1&amp;&gt;(testr); d1.derived1specific(); } catch(std::bad_cast&amp;){} try{ const derived2&amp; d2 = dynamic_cast&lt;const derived2&amp;&gt;(testr); d2.derived2specific(); } catch(std::bad_cast&amp;){} } </code></pre> <p>What you wanted to do, which I would not recommend you, is something like:</p> <pre><code>auto doNothing = [](){return;}; (test-&gt;type()==1?(((derived1*)test)-&gt;derived1specific()):doNothing()); </code></pre> <p>You can try the full code <a href="http://coliru.stacked-crooked.com/view?id=357c3c8e2e9fe23bf1a4d5c6a55f7ff4-72f1b4de714fd92d7b53b2e51b310d82" rel="nofollow">here</a>.</p> <p>As for your comment: you can substitute the macro with a free-function (which is advisable anyway)</p> <pre><code>void derived1specific(base* b){ if(derived1* d1 = dynamic_cast&lt;derived1*&gt;(b)) d1-&gt;derived1specific(); } </code></pre> <p>which does exactly what your code wants to do: execute the derived specific function if and only if it is appropriate; you simply call it like:</p> <pre><code>derived1specific(test); </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.
    1. 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