0

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();

6
  • 3
    The short answer is that the compiler knows which type you've declared, and treats the variable according to that type (e.g. generating integer instructions for int variables and floating-point instructions for float variables). The long answer would fill a book. Aug 28, 2014 at 1:35
  • This is covered in any decent C++ book or reference site. You should find one; Google and Bing are both excellent at searching for web sites, and places like Amazon allow you to search for books on a topic and even sort the results by reviewer ratings. (Short answer: The compiler is designed to understand the code and make the proper allocations and associations.)
    – Ken White
    Aug 28, 2014 at 1:37
  • 1
    I mean, the ability to do this is pretty much the main purpose of compilers.
    – Red Alert
    Aug 28, 2014 at 1:38
  • That book being similar to the "Dragon Book". en.wikipedia.org/wiki/… Aug 28, 2014 at 1:38
  • both have 4 bytes allocated in memory / but a pointer is 4 bytes not necessarily, never make assumptions about the size of fundamental types.
    – user657267
    Aug 28, 2014 at 1:38

1 Answer 1

0

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).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.