class derived : public base
s.append(" with added stuff.");
std::cout << s;
std::string s="executing derived";
base* b = new derived();
executing derived with added stuff.
I understand why a pointer to base can call the overloaded execute() function. What I don't understand is that, with b being a pointer to base, how does the overloaded execute() function access members (s and print()) that are only defined in the derived class?
I envisioned the workings of base pointers as only being able to access the size of a base-object in memory, but that doesn't seem to be the full story?
Thanks very much in advance for your help, it's greatly appreciated as always.
A virtual function is indirectly called via the virtual function table for the provided signature (in your case the execute() function). Since all constructors previously placed their virtual function pointer in the virtual table the last derived class wins, i.e. that function will be called. In your case execute() from derived
Check it out: derive another time (from derived) and implement execute() again
Thanks for following up - I think I understand the vtable lookup, but my question was: how can a pointer to a base object execute a function which changes member data only defined in a derived class. In other words, how can a pointer to base, call execute() which changes s, which is not defined in base.
What I took away from the Wikipedia article you linked to was that the this pointer is passed to the function (as it is implicitly to any member function), allowing access to derived's private members. Then again, I'm not really sure how that would work - now I'm confused again. Here's how in my mind the call of b->execute() is done:
- base has defined execute() as a virtual function, so vtable loopup occurs
- execute is overridden in derived, so the vtable will contain a pointer to derived::execute
- the code at the address of that pointer is executed, after passing the this parameter to it - the called code alters s and calls print()
- function returns
It's this penultimate step I don't understand, because doesn't the base pointer only point to the segment of a derived object they have in common? If so, how can a base pointer call a function that would alter values outside of that segment? I would guess the this-ptr, but that would mean the this-ptr is always of type derived?
> how can a pointer to a base object execute a function which changes
> member data only defined in a derived class. In other words,
> how can a pointer to base, call execute() which changes s, which is not defined in base.
It is the responsibility of the implementation to ensure that when a non-static member function of derived is called (polymorphically via a pointer or reference to base), the this pointer is adjusted correctly. The function must be called with the type of the this pointer being 'pointer to derived'. That is, this must point to a valid object of type derived.