LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 8

Size of classes with and without virtual functions Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links