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;
}
Make virFun take a reference, not an A object by value:
No need to override virFun in class B, since it uses the argument obj in both cases
In fact, virFun could be a static function. The name is confusing since it isn’t even a virFun (virtual function) – it is a regular function that uses a virtual function.
See it live on http://liveworkspace.org/code/1624496ced29eb4683f5b19072f72f60