Search code examples
c++memoryallocation

How declarations works in memory


Let's assume that two variables:

  int x = 10;
  float y = 10.5;

both have 4 bytes allocated in memory, but how this works, since operations with int and float are different?

Following the same logic:

  Animal * d = new Dog ();

Animal is a pointer that points to a dog, but a pointer is 4 bytes and stores an address. How he knows he is an animal? So later you can do d.sound();


Solution

  • The declaration tells the compiler two things:

    1. How much memory to allocate for the variable.

    2. What kind of code to generate when performing calculations using the variable.

    So when you use an expression like x + 6, the compiler will emit code that makes use of the integer addition instruction of the CPU. When you use y + 6, it will emit code that makes use of the floating point addition instruction.

    Type declarations are also use to determine when to convert values if you call a function that expects a different type than the variable, or perform assignments between variables of different types. E.g. if you have

    void floatfun(float z);
    

    and you call floatfun(x), the compiler will generate code that computes the floating point equivalent of x's value, and pass that to the function.

    When the type is a struct or class, the declaration further allows the compiler to determine which members can be used, and how to translate member names to code that accesses them. The compiler also knows about the relationship between base classes and derived classes, so it knows that you can assign Dog* to Animal*, and performs the appropriate transformations (in C++ this involves a data structure called the vtable).