Note that there are some explanatory texts on larger screens.

plurals
  1. POVirtual Calls using address of pure virtual member. Is it legal?
    primarykey
    data
    text
    <p>I read sometime back (probably on c.l.c++.moderated) that virtual function calls can be templatized. I tried something on the following lines.</p> <pre><code>#include &lt;iostream&gt; template&lt;class T, class FUN&gt; void callVirtual(T&amp; t, FUN f){ (*t.*f)(); } struct Base{ virtual ~Base(){} virtual void sayHi()=0; }; struct Derived : public Base{ void sayHi(){ std::cout &lt;&lt; "Hi!" &lt;&lt; std::endl; } }; void Test(){ Base* ptr = new Derived; callVirtual(ptr,&amp;Base::sayHi); } int main() { Test(); return 0; } Output: Hi! </code></pre> <p>The templatized method though given the address of pure virtual base member method at compile time calls the correct method at runtime. Is it legal in standard C++ to take address of a pure virtual member?</p> <p>Thanks in advance</p> <p><strong>EDIT-1:</strong> I removed the second part of the question 'how does it work?'. Looks like that is what is catching attention.</p> <p><strong>EDIT-2:</strong> I searched c.l.c++.moderated and came across this <a href="http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/5ddde8cf1ae59a0d" rel="nofollow noreferrer">link</a> (<a href="http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/5ddde8cf1ae59a0d" rel="nofollow noreferrer">http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/5ddde8cf1ae59a0d</a>). The consensus seems like since the standard does not restrict it, it is vaild.</p> <p><strong>EDIT-3:</strong> After reading the codeproject article (thanks to ovanes), i am thinking that the compilers do some magic. Since virtual functions are implemented via vtable (which is compiler specific), taking address of a virtual function always gives the offset in the vtable. Depending on the 'this' pointer used, the appropriate function (whose address is at the offset) is called. I am not sure how to vindicate this though as the standard does not say anything abt it!</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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