Question 8
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
struct A { int x; };
struct B { int x; virtual void f() {} };
struct C { int x; virtual void f() {} virtual void g() {} virtual void h() {} };
struct D : B { void f() override {} };
int main() {
std::cout << sizeof(A) << ' ' << sizeof(B) << ' ' << sizeof(C) << ' ' << sizeof(D) << '\n';
return 0;
}
- A 4 16 16 16 Correct
- B 4 12 28 12
- C 4 8 8 8
- D 4 16 32 24
Correct Answer: Option A
A polymorphic object holds one hidden vptr (8 bytes) no matter how many virtual functions there are; with the int and alignment padding, B, C and D are all 16 bytes.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!