1. Introduction
If
you specify the Following statement in your C++ code file, what does compiler
know about it?
int
x;
The above statement says the compiler you declared
a variable of type integer. So it reserved some space large enough to hold the
integer numbers. So what is Definition? Some people say that whenever you
declare something you should have been defined it previously. That is correct.
Where is the definition for integer? I do not define it. The types like int,
float, and char are already pre-defined by the
language itself and hence the compilers know about it.
2. Definition
A
definition is nothing but specifying your own type making the combination of
predefined types. Say for example if you tell the structure dept is having two
pre-defined variables of type integer and float to store the department id and
totalsalary, then you actually provided a definition for the struct dept.
When
compiler sees it, it just learns about the type and knows the definition
of it. At this moment it will not allocate any space for it.
3. Declaration
Declaration is specifying the compiler that you are
going to use a specific type (pre-defined or the one defined by you) so
allocate a space required for it. And compiler knows how much space to allocate
for the declared variable, as it knows the space requirement from
the definition of the type.
So
this is why a definition goes first before the actual declaration. This is why
you define the structure or class at the beginning of the file and start using
it by declaring the variable of that type after the definition. And, to avoid
the mistakes we actually place the definitions in the header files (.h) and
#include it in the source files (.cpp). Note that the #include
<abc.h> at the beginning of the file actually replaced the file
content at the top. Hence, the definitions are at the top of CPP file.