Interview Question
Basically
PolyClass one;
would look like [vtable][PolyClass's fields] and
PolyClass many[2];
would look like [vtable][PolyClass's fields][PolyClass's fields].
If we take the address &many[1], then it doesn't begin with a vtable; any code that uses it now has to become aware of its storage details.
Its okay if was derived class object by itself that had virtual functions.
But imagine a case where Base * b = new Derived();
Here later when b is used, how would it knw which Vtable to use? that of Base class or derived class?
Cause later the same b can point to someother object of say Base class then.. or even later Derived2 class.
Hence each object has first allocation of Vtable pointer then other data.
So even if it later pointed by some other class pointer it would knw which object virtual functions are really valid.
Polymorphism is a run time feature. At run time the appropriate virtual function is invoked (using vptr & vtbl). For non-virtual functions the decision to invoke which function is made at compile time and hence the compiler does not generate any vtbl/vptr for it
Well you could, but when you took the address of an array element, it wouldn't look like other objects of that type. In theory the compiler could handle this, but in practice that would be a waste of the compiler writers' time.
- Anonymous August 03, 2010