Tuesday 7 November 2017

What is the difference between declaration and definition of a variable in C++?

My question stems from studying href="http://www.amazon.in/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876">Effective
C++ by Scott Meyers.

In Item II of that book, following
is written :




To
limit the scope of a constant to a class, you must make it a member and, to ensure
there's at most one copy of the constant, you must make it a static member.




That is correctly
written. Then immediately the following example is given :



class GamePlayer
{
private:

static const int NumTurns = 5;
int
scores[NumTurns];
....

};


Then the following
is written pertaining to the above example :




What you see
above is a declaration and not a definition of
NumTurns.





My
First question is : What is the meaning of this statement
?



Immediately after that the
following is mentioned :





Usually C++ requires that you provide a definition for anything you use, but
class specific constants that are static and of integral type (e.g - integers, chars,
bools) are an exception. As long as you don't take their address, you can declare them
and use them without providing a definition. If you do take the address of a class
constant, or if your compiler incorrectly insists on a definition even if you don't take
the address, you provide a separate definition like this :
const
int GamePlayer::Numturns; //definition of
NumTurns





Why
now it is a definition and not a declaration
?



I understand the difference in
the context of a function but do not understand it in the context of a regular variable.
Also, can someone expand on what the author means by




... if you do
take the address of a class constant, or if your ..
part of the above quoted
paragraph
?





P.S :
I am a relatively newbie in C++.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...