C++ sizeof Trap: Virtual Functions and Memory Bloat

C++ Bits: Post 3 The sizeof Trap: Why Is Your Class Bigger Than You Think? Quick what's the output of the code in the image given below? If you said both are 4... you just fell into one of C++'s most classic interview traps. sizeof(A) is indeed 4 bytes , just one int, nothing else. But sizeof(B)? On most 64-bit systems, it's 16 bytes. Not 4. Not even 12. Where did the extra 12 bytes come from? The moment you add the virtual keyword, the compiler secretly injects a hidden pointer called the vptr (virtual pointer) into every object of that class. This vptr points to a vtable , a per-class lookup table of function pointers that enables runtime polymorphism. On a 64-bit system, that hidden pointer is 8 bytes. So your object is now 4 (int) + 8 (vptr) = 12 bytes. But wait , the compiler also adds padding to align the object to an 8-byte boundary. So 12 becomes 16. Let's break it down: → class A: [int x = 4B] → Total: 4 bytes → class B: [vptr = 8B] + [int x = 4B] + [padding = 4B] → Total: 16 bytes One keyword. Triple the memory. And if you're allocating millions of objects, that difference isn't trivial ,it's a design decision. This is exactly why some performance-critical codebases (game engines, embedded systems) deliberately avoid virtual functions. The overhead isn't the virtual call , it's the memory bloat across millions of objects. Next time someone says "just make it virtual," remember: polymorphism isn't free. The compiler is quietly billing you 8 bytes per object, plus padding. What's the sneakiest sizeof result you've encountered in an interview or codebase? Let's hear it below. #CPP #Cplusplus #SoftwareEngineering #TechTrivia #Programming #BackendDevelopment

  • No alternative text description for this image

Thank you for post, as you’ve stated virtual come with memory overhead. So any suggestions on how to implement inheritance while avoiding virtual?

Like
Reply

To view or add a comment, sign in

Explore content categories