C++ polymorphic call without explicit pointer
If I have base class:
开发者_如何学JAVAstruct Base
{
void foo()
{
bar();
}
virtual void bar()
{
}
};
And derived class:
struct Derived : public Base
{
void bar()
{
cerr << "Derived here\n";
}
};
It is happen that when write this code:
Derived d;
d.foo();
I will see printing "Derived here" - since Derived::bar
was called. But I did not call via pointer to base, but polymorphism working here. Why? Is it because the call to bar
in Base::foo
is implicitly actually to this->bar()
and bar
is finding in vtable of class?
Your guess is precisely correct (although bear in mind that the C++ standard says nothing about vtables).
Is it because the call to bar in Base::foo is implicitly actually to this->bar() and bar is finding in vtable of class?
The d.foo()
call actually does (&d)->foo()
, so foo()
receives a this
pointer, looks up the vtable, and finds the correct bar()
implementation.
In other words, to foo()
, it doesn't matter whether it was called via a pointer or not. It always gets a this
pointer and works the same way regardless.
You were half right. It isn't an explicit pointer but it does look in the vtable for the first entry for that function. Since the derived class supplied a new entry for that function you are calling the derived function. Polymorphism works regardless of pointers - it's just all the examples use pointers to show how easy it is to decouple using polymorphism.
1) why are you defining methods in structs?
2) yep, polymorphism is what gets you to call Derived::foo()
rather than Base::foo()
because you declared it virtual. Indeed, this allowed the code to find the correct method in the vtable of the class (or whichever pointer table structure the compiler creates for you to keep track of the polymorphic methods.)
精彩评论