Polymorphic C ++ call without an explicit pointer

If I have a base class:

struct Base { void foo() { bar(); } virtual void bar() { } }; 

And the derived class:

 struct Derived : public Base { void bar() { cerr << "Derived here\n"; } }; 

It happens that when writing this code:

 Derived d; d.foo(); 

I will see the print "Produced here" - as Derived::bar was called. But I did not call through the pointer to the base, but polymorphism worked here. What for? Is this because the call to bar in Base::foo implicitly actually equal to this->bar() and is the bar in the vtable of the class?

+4
source share
4 answers

Your hunch is exactly correct (although remember that the C ++ standard says nothing about vtables).

+4
source

Is this because calling bar in Base :: foo is implicitly actually located in this → bar (), and bar is in the vtable of the class?

Actually, the call to d.foo() has (&d)->foo() , so foo() gets the this pointer, looks for vtable, and finds the correct implementation of bar() .

In other words, to foo() , it doesn't matter if it was called with a pointer or not. It always gets the this pointer and works independently of it.

+1
source

You were half right. This is not an explicit pointer, but it looks in the vtable for the first entry for this function. Since the derived class provided a new entry for this function, you call the derived function. Polymorphism works independently of pointers - it's just that all examples use pointers to show how easy it is to share the use of polymorphism.

0
source

1) why do you define methods in structures?

2) yep, polymorphism is a call to Derived::foo() instead of Base::foo() , because you declared it virtual. In fact, this allowed the code to find the correct method in the vtable of this class (or whatever pointer structure that the compiler creates for you to track polymorphic methods.)

0
source

All Articles