Harishvk27’s Weblog

July 12, 2008

Method Overloading Doesn’t Work in C++ when called from base class constructor

Filed under: C++ — harishvk27 @ 4:46 am

#include “stdio.h”

class A {

public:

A() {

this->myPrint();

}

virtual void myPrint() {

printf(“A:%s()\n”,__FUNCTION__);

}

};

class B: public A {

public:

B() {

}

void myPrint() {

printf(“B:%s()\n”,__FUNCTION__);

}

};

main()

{

B b1; // prints A:myPrint

b1.myPrint(); // prints B:myPrint

}

The reason is when A:A() executes, the object is still of type A. It only becomes the obect of type B, when code in B:B() is entered.

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.