Note that there are some explanatory texts on larger screens.

plurals
  1. POwhat is "capability query" in dynamic_cast context and why is this useful?
    text
    copied!<p>I am reading some C++ material on dynamic_cast and there the following practice is considered bad:</p> <pre><code>class base{}; class derived1 d1 :public base{}; class derived2 d2 :public base { public: void foo(){} }; void baz(base *b) { if (derived2 *d2= dynamic_cast&lt;derived2 *&gt; (b) ) { d2-&gt; foo(); } } </code></pre> <p>The remedy to this is to use the "capability query" using an empty pure virtual base class like following:</p> <pre><code>class capability_query { public: virtual void foo()= 0; }; class base{}; class derived1 d1 :public base{}; class derived2 d2 :public base, public capability_query { public: virtual void foo(){} }; void baz(base *b) { if (capability_query *cq= dynamic_cast&lt;capability_query *&gt; (b) ) { cq-&gt; foo(); } } </code></pre> <p>My 1st question is why is the first code block considered bad? The way I see it <code>foo</code> is only executed if d2 can be successfully downcasted from b in the <code>baz</code> function. So what is the issue here?!</p> <p>My 2nd question is why is the second code block considered good? and how does this fix the issue, which I don't understand in the first place. </p> <p>FYI, my google search for <code>capability query</code> returned <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Capability_Query" rel="nofollow">http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Capability_Query</a> which seems to be basically code block1 and not code block2. I still don't get why an additional empty base class is considered a better practice?</p> <p><strong>EDIT:</strong> here is the best possible answer I can think of.Since inside <code>baz</code> I am downcasting to a pointer type and not reference, in case the downcast is not successful , I will get a Null pointer and not std::bad_cast. So, assuming the cast goes wrong and I do get NULL pointer , but what if I am not supposed to execute <code>Null-&gt;foo</code> and if I may forget to test for NULL, so code block 1 could be a problem. The way code block 2 fixes this, is by adding an empty class. Even if </p> <pre><code>dynamic_cast&lt;capability_query *&gt; (b) </code></pre> <p>fails and I get a null pointer , you cannot execute <code>null-&gt;foo</code> since inside <code>capability_query</code> class this <code>foo</code> method is pure virtual. This is just a conjecture , but may be I am on the right path??!!</p>
 

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