Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this method call virtual like I was expecting?

I want to ask what happen, when I use virtual functions without pointers ? for example:

#include <iostream>
using namespace std;
class Parent
{
 public:
   Parent(int i) { }
   virtual void f() { cout<<"Parent"<<endl; }
};

class Child : public Parent
{
 public:
   Child(int i) : Parent(i) { }
   virtual void f() { Parent::f(); cout<<" Child"<<endl; }
};

int main()
{
    Parent a(2);
    Parent b = Child(2);
    a.f();
    b.f();
    return 0;
}

^^ Why doesn't it work ? Where can I find something about how virtual methods really work?

like image 305
yProgrammer Avatar asked Nov 26 '25 16:11

yProgrammer


1 Answers

This effect is called "slicing."

Parent b = Child(2); // initializes a new Parent object using part of Child obj

In C++, the dynamic type may only differ from the static type for references or pointers. You have a direct object. So, your suspicion was essentially correct.

like image 158
Potatoswatter Avatar answered Nov 29 '25 04:11

Potatoswatter



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!