Skip to content

Another C++ quiz, simpler


Did you ever think, what happens if you take a member pointer to a virtual function of a class, and then call it on another instance of derived class (that overrides that member)?

What if you do the same for nonvirtual function?

Here’s a test:

#include <iostream>

class A
{
  public:
  virtual void f() { std::cout << “A::f()\n”; };
  void g() { std::cout << “A::g()\n”; };
};

class B : public A
{
  public:
  virtual void f() { std::cout << “B::f()\n”; };
  void g() { std::cout << “B::g()\n”; };
};

typedef void (A::*VirtualFunctionPointer) ();

int main()
{
  A a;
  B b;
  B* pb = &b;

  VirtualFunctionPointer p = &A::f;
  (pb->*p) ();

  p = &A::g;
  (pb->*p) ();
  return 0;
}

Answer is in comments.

Please bookmark this post: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • StumbleUpon
  • Live
  • Google
  • description
  • YahooMyWeb
  • Technorati

One Comment

  1. Victor Sergienko

    Both MSVC and gcc print:

    B::f()
    A::g()

    which means member function pointer keeps both function address and VMT index.
    And probably a flag telling if it’s virtual.

    Posted on 14-May-08 at 0:48 | Permalink

One Trackback/Pingback

  1. […] take another, simpler C++ quiz about member pointers. Please bookmark this post: These icons link to social bookmarking sites where readers can share […]

Post a Comment

Your email is never published nor shared.