In my C++ program:
#include<iostream.h>
class A
{
public:
virtual void func()
{
cout<<"In A"<<endl;
}
};
class B:public A
{
public:
void func()
{
cout<<"In B"<<endl;
}
};
class C:public B
{
public:
void func()
{
cout<<"In C"<<endl;
}
};
int main()
{
B *ptr=new C;
ptr->func();
}
the statement should call B::func(). However, the function, C::func() is called. Please throw some light on this. Once the virtual keyword is removed in 'class A', this does not happen anymore.
Once declared virtual function will be virtual in all derived classes (no matter if you explicitly specify it or not). So func() is virtual in A, B and C classes.
For the basics you should read C++ FAQ Lite on Virtual Functions.
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With