Saturday 29 April 2017

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

My question stems from studying 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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...