Virtual Functions
Consider the following:
#include <iostream>
using namespace std;
class A
{
public:
virtual void func1( int a ){ cout<<"A::func1"; }
virtual void func2( int i=20 ){ cout<<i; }
};
class B: public A
{
public:
void func1( float a ){ cout<<"B::func1"; }
void func2( int i=40 ){ cout<<i; }
};
int main(int argc, char* argv[])
{
A* pb=new B;
pb->func1(1);
pb->func2();
return 0;
}
Can you guess the output for the same?
pb->func1(1) => A::func1!! This is so, because, B::func1 hides( as a result of overloading) A::func1, rather then override it. And in C++, overload resolution is done on the static type, as it is done at compile time.
pb->func2() => 20!! This is so because, although B::func2 is called, the compiler picks up the default value from the base class. So, default values should be the same down the class hierarchy.
As an aside, the C++ standard states that built in conversions have more priority then user defined conversions.
Source: http://www.gotw.ca/gotw/005.htm
Labels: gotw, virtual functions
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home