Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ virtual function confusion

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;
}
like image 963
Jimm Avatar asked Dec 19 '25 00:12

Jimm


1 Answers

void virFun(A obj);

For virtual functions to work you need to pass objects by reference or by pointer to ensure that you're always working with the original object.

void virFun(const A &obj);
void virFun(const A *obj);

Otherwise virFun() will receive a copy of your object, which ends up "slicing" it and losing the derived class's information. The copy has A's vtable and is missing B's extra fields. This is usually a disaster.

As a general rule, pass objects around using T& or const T& rather than plain T. Aside from the slicing problem, it's also more efficient.

like image 167
John Kugelman Avatar answered Dec 20 '25 13:12

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!