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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With