Re: Virtual binding question

[ Follow Ups ] [ Post Followup ] [ CS2704 Web Discussion Board ] [ FAQ ]

Posted by William D McQuain on December 18, 2001 at 10:13:56:

In Reply to: Virtual binding question posted by Jon on December 17, 2001 at 16:09:31:

: I have a question if anyone has a good answer I'd appreciate it. On the homework on problem number 24 there is a pointer of the main base object type (Base) pointing to an E object. On line 10 polymorphism is invoked and the call to the function G() binds.
: My question is basicly does because this is a pure virtual function with no implementation in Base does that make it bind to the right one without trying to bind to the D layer first?

The fact that Base::G() is *pure* virtual doesn't come into play (initially at least). What matters is that Base::G() is virtual, and that turns on runtime binding of the call.

At runtime, the object targeted by the pointer stores a pointer to the virtual function table for the class to which that object belongs (E in this case). Now, the vtable for the class E will store a pointer to the appropriate implementation of G()... which one will that be?

Since the class E implements its own G(), overriding the one inherited from the class D, the vtable for the class E points to E::G() and that's what gets called.

If E didn't implement its own G(), then the vtable would point to the one inherited from the class D, and so D::G() would be called.

If neither E nor D implemented G(), then all three classes would be abstract, since each would have a *pure* virtual function (declared in Base and inherited by D and E), and the code would not compile since it wouldn't be possible to create an object of type E (or D or Base).

: Is that the reason that it binds the way it does? and is that the way the binding in that situation works?

: Thanks.

Follow Ups:

Post a Followup




Optional Link URL:
Link Title:
Optional Image URL:

[ Follow Ups ] [ Post Followup ] [ CS2704 Web Discussion Board ] [ FAQ ]