Thursday, October 18, 2012

bit of fun with C++ virtual functions

#include ...
class A {
public:
   A() {  f(); }
   virtual void f() { printf("A func!\n"); }
};

class B : public A {
public:
   B() : A() { }
   virtual void f() { printf("B func!\n"); }
};

int main() {
   A a;
   B b;

   return 0;
}

I had written a code similar to the above template. I had naively thought that the above code will print 'B func!' when the instance of B is created. However this is not the case. I guess the issue here is that if you tend to call a member function that is virtual from a base class constructor, the base class implementation will be called as the v-table initialization has not yet been done (this is at-least the case with g++ compiler, not sure how other compilers work). This is further clear when you try and make the function f() in base class A pure virtual, the compiler complains with an error.

Have fun!
 

No comments: