I am learning about virtual functions and i am very confused with the results of the below program
I was hoping that both a1.virFun(b1)
and b1.virFun(b1)
should return "hello from B", but the program returns "hello from A". This is contrary to my understanding. Can you please explain why b1.sayHello()
is not being invoked, even when i am passing b1 as argument and b1.sayHello()
is virtual function.
#include<iostream>
using namespace std;
class A
{
public:
virtual void sayHello();
void virFun(A obj);
};
class B : public A
{
public:
void virFun(A obj);
virtual void sayHello();
};
void A::sayHello()
{
cout << "hello from A" << endl;
}
void B::sayHello()
{
cout <<"hello from B" << endl;
}
void A::virFun(A obj)
{
obj.sayHello();
}
void B::virFun(A obj)
{
obj.sayHello();
}
int main()
{
A a1;
B b1;
a1.virFun(b1);
b1.virFun(b1);
return 0;
}