ProgrammingVery hardWipro · Cognizant technical pattern

On a typical 64-bit compiler (8-byte pointers, 4-byte int, natural alignment), what does sizeof(P) print?

On a typical 64-bit compiler (8-byte pointers, 4-byte int, natural alignment), what does sizeof(P) print?
class P {
    int id;
public:
    virtual void show() {}
};
  1. A. 4
  2. B. 12
  3. C. 8
  4. D. 16

Correct answer: D. 16

A class with a virtual function gets a hidden vtable pointer (8 bytes). Add the 4-byte int and pad to a multiple of the 8-byte alignment: 8 + 4 + 4 = 16. 12 forgets padding; 4 ignores the vptr. (The exact value is implementation-defined, but this is the common layout.)

More OOP with C++ and Java questions

Exams that ask this topic