Reputation: 127
Late binding occurs only with virtual functions, and only when you’re using an address of the base class where those virtual functions exist.
This is an extract from a famous text book.
My question is...what exactly does the author mean by 'using an address' ?
Upvotes: 0
Views: 83
Reputation: 106068
The relevant scenarios are when you have a pointer or reference with a static type of pointer-to-Base or reference-to-Base, regardless of whether the pointer or reference is a local variable, a function parameter, member variable etc..
// accessed via pointer...
Base* p = new Derived(); p->fn(); // (ref.1)
void f(Base* p) { p->fn(); } Derived d; f(&d);
// accessed via reference...
const Base& r = static_derived;
void f(Base& b) { b.fn(); } Derived d; f(d);
Late binding occurs only with virtual functions, and only when you’re using an address of the base class where those virtual functions exist.
The statement is misleading in two ways:
Late binding may occur under the specified circumstances, but the optimiser's allowed to bind at compile or link time instead if it can work out the dynamic type involved. For example, if both lines of code in (ref.1) above appeared together in a function body, the compiler can discern that p
addresses a Derived
object and hardcode a call straight to any Derived::fn()
override, or failing that the Base-class implementation.
The situations above involved pointers and references. As far as the C++ Standard's concerned, the mechanisms used to implement references are left unspecified and we humble programmers shouldn't assume they're effectively pointers with different notations for use, so we shouldn't consider them to store the "address" of the variable they reference, but thinking of them as glorified pointers storing addresses is generally practical and the quoted statement's lumped them in with pointers as mechanisms "using an address".
Upvotes: 1
Reputation: 17415
I guess that the emphasis is not on using an address, which would be wrong since a reference would do as well. Rather, the point is that the static type of the address or reference is that of a "base class where those virtual functions exist". This is not always the case when you have multiple baseclasses or when the baseclass hase a baseclass itself where the memberfunction in question does not exist.
Upvotes: 0