**Read the below mention code **
#include<iostream>
using namespace std;
class FR
{
public :
virtual int fun()
{
cout<<"In FR Class "<<endl;
}
int Threading()
{
fun();
}
};
class FD : public FR
{
public :
int fun()
{
cout<<" In FD class "<<endl;
}
};
int main()
{
FD obj ;
obj.Threading();
}
Here,output of this is "in FD class".
here we have inheritance the FR class into FD class,so all property from the FR class is inheritade from the based class,
but when we call the Threading() function using the FD object than it will called the based class but for Threading class Fun() function is available as virtual and Fun definition is also available so
why it not classed the based class Fun() function.
I'm expecting that when we called the Threading() function than it should be called the class FR Fun() function not class FD Fun().
Actual OutPut : "In FD Class"
Expected OutPut : "In FR Class"
This is known as virtual dispatch and is basically just what
virtualmeans not more. The method to be called is determined by the dynamic type of the object.You can think of the call as having a
this->:When
Threadingis called on an object of typeFDthen in above codethisis aFR*but the dynamic type of the object to whichthispoints isFD. Hence when the virtualfun()is called it callsFD::fun().If you do not want virtual dispatch for
funremove thevirtual. Then your code will print "In FR Class".