IBM Interview Question
Developer Program EngineersThe minimum size u need to represent an object is 1 byte. That's why first one returned 1 byte.
Second one contains a Vtbl entry that's why the answer is 4.
first case: 1 byte so that no two objects have the same address in the memory
second case: since it has a virtual function, the compiler will add a virtual table and a virtual pointer...but since each class has one virtual pointer per class and not per object, the size of the object should still be 1 bytes...
any suggestions?
I think virtual pointer is declare in first class in hierarchy who has introduce virtual function.
Now any derive class that override base class virtual function or introduces new virtual function they use same virtual pointer. And update pointer in constructor & destructor of class.
And virtual pointer take size of one pointer unit (32 bit for 32 bit machine) in every object.
In my opinion, as everyone has already agreed that a class with virtual function requires a virtual table. And we have to store pointer to that virtual table somewhere for the class. Now as we know a pointer has a size of 4 bytes (depending on the underlying hardware, i.e. how many bits are required to represent a physical address). So class with virtual function has a size of 4 bytes.
Should n't we add size of empty class + size of vtable pointer in second case. in that case ans for second case is 5 bytes
If we have vtable pointer inside a class, we do not need anymore 1 byte difference to prevent object creation at the same place in memory. Thus, the size remains 4 bytes (i.e. more that 1 byte).
No, you are wrong. Each class with virtual function has a vtble and virtual pointer for each object it instantiates. Thats why each object is associated with a separate vtbl pointer. Hence its size is 4 bytes.
Note just a class has no size. Class is merely a blue print. Its objects have sizes.
- viswathsen April 10, 2011