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() {}
};- A. 4
- B. 12
- C. 8
- 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
- What is printed? java class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } } class C…
- What is printed? java class P { P() { show(); } void show() { } } class C extends P { final int a = 5; int b = 7; final String s = "s"…
- What is printed? java // static methods of the main class: static int f() { int x = 1; try { x = 2; throw new IllegalStateException(); }…
- What is printed? java Long l = 127L; Integer i = 127; System.out.print(l.equals(127) + " "); System.out.print(l.equals(127L) + " ")…
- What is printed? java // static methods of the main class: static void f(long x) { System.out.print("long "); } static void f(Integer x) {…
- What happens when this code runs? java List<String> strs = new ArrayList<>(); strs.add("a"); List raw = strs; raw.add(42)…