How much memory do objects use?

Most objects occupy more than a single byte of memory. An object might use 1, 2, 4, 8, or even more consecutive bytes depending on its data type.

When you work with variables in your code, the compiler handles these details automatically. It knows exactly how many bytes each type requires and generates the appropriate machine code.

Understanding object sizes is valuable for two reasons:

Storage capacity: The size of an object determines how many different values it can represent.

  • 1 bit holds 2 values (0 or 1)
  • 8 bits (1 byte) hold 256 values
  • 16 bits (2 bytes) hold 65,536 values
  • 32 bits (4 bytes) hold over 4 billion values

Memory constraints: Each object you create consumes memory for its entire lifetime. While usually negligible, this matters for programs handling massive amounts of data.

Note
Don't obsess over minimizing memory usage. Focus on writing clear, maintainable code first. Optimize memory usage only when you can demonstrate a meaningful benefit.

Type sizes in C++

C++ doesn't specify exact sizes for each data type - only minimum requirements. Here are the typical sizes on modern systems:

Category Type Minimum Size Typical Size
Boolean bool 1 byte 1 byte
Character char 1 byte (exact) 1 byte
wchar_t 1 byte 2 or 4 bytes
char16_t 2 bytes 2 bytes
char32_t 4 bytes 4 bytes
Integer short 2 bytes 2 bytes
int 2 bytes 4 bytes
long 4 bytes 4 or 8 bytes
long long 8 bytes 8 bytes
Floating Point float 4 bytes 4 bytes
double 8 bytes 8 bytes
long double 8 bytes 8, 12, or 16 bytes

The sizeof operator

To discover the actual size of types on your specific system, C++ provides the sizeof operator. This operator accepts either a type or a variable and returns the size in bytes.

#include <iostream>

int main()
{
    std::cout << "Size of int: " << sizeof(int) << " bytes\n";
    std::cout << "Size of double: " << sizeof(double) << " bytes\n";
    std::cout << "Size of char: " << sizeof(char) << " bytes\n";
    std::cout << "Size of bool: " << sizeof(bool) << " bytes\n";

    return 0;
}

Sample output on a typical 64-bit system:

Size of int: 4 bytes
Size of double: 8 bytes
Size of char: 1 bytes
Size of bool: 1 bytes

You can also use sizeof with variables:

int count{};
std::cout << "count occupies " << sizeof(count) << " bytes\n";
Note
Attempting to use sizeof on an incomplete type like void produces a compilation error.

Performance considerations

On modern computers, operations involving fundamental types are extremely fast. You generally don't need to worry about performance when using or copying these types.

Interestingly, smaller types aren't always faster than larger ones. CPUs are often optimized for specific data sizes (commonly 32 bits). On such systems, a 32-bit int might actually be faster to process than a 16-bit short.