22.- Curso C++ Básico. El tamaño de los Objetos. De Void a sizeof.
Understanding Object Sizes in C++
The Void Type and Its Usage
- The void type represents "no type" in C++, indicating that a variable cannot be defined as void.
- Functions that do not return a value are often declared with void, and using a return statement to return a value from such functions will lead to a compilation error.
- Using void for functions without parameters is discouraged in modern C++ due to its origins in C; empty parentheses are preferred instead.
- Void pointers are an advanced topic not covered until the section on pointers later in the course.
Memory Organization and Object Size
- Modern computer memory is organized into bytes, each with a unique address, but objects can occupy multiple bytes (2, 4, 8, or more).
- Objects should be viewed as Lego containers of varying sizes rather than isolated mailboxes; each byte has its own address.
- The size of an object depends on its assigned data type; the compiler manages memory allocation based on this type.
Information Capacity Based on Object Size
- The amount of information an object can hold is determined by its size: one bit holds two values (0 or 1), while n bits can hold 2^n values.
- A byte (8 bits) can represent 256 different values; larger objects increase the number of unique values they can store exponentially.
- Objects using more bytes allow for greater storage capacity for unique values, which will be explored further when discussing fundamental integer types.
Determining Data Type Sizes
- The memory occupied by fundamental data types varies based on computer architecture (32-bit vs. 64-bit systems).
- C++ guarantees minimum sizes for fundamental data types but actual sizes may differ across machines and compilers.
Using the sizeof Operator
- The
sizeofoperator returns the size of a data type or variable in bytes; it cannot be used with void since it has no size.