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.
Try the following:
std::auto_ptr<Parent> b = new Child(2);
In your code you copy part of Child
object to b
. This is so called object slicing.
Virtual function mechanism is enabled only if the virtual function is called through either an appropriate reference or an appropriate pointer. Note that virtual function call mechanism is suppressed in constructor/destructor or while using the :: operator.
If the code is as shown below, virtual function mechanism will be enabled.
Child c;
Parent &a = c;
a.f();
Without pointers, the call is statically bound, even if it is a virtual function call.
EDIT 2:
$10.3/6 - [Note: the interpretation of the call of a virtual function depends on the type of the object for which it is called (the dynamic type), whereas the interpretation of a call of a nonvirtual member function depends only on the type of the pointer or reference denoting that object (the static type) (5.2.2). ]
精彩评论