the book "Effective C++" have a item introduce cosnt,but a question i dont understand clearly.

class GamePlayer {
private:
	static const int NUM_TURNS = 5; // constant eclaration 
	int scores[NUM_TURNS];		// use of constant
	...
};

const int GamePlayer::NUM_TURNS;	// mandatory definition;
		// goes in class impl.file

why must define the NUM_TRUNS in static ?

Recommended Answers

All 5 Replies

const is short for constant.An constant must be initialised when it is declared and it cannot be changed.

In a class you cannot declare a member as datatype data_var = some_value since it's against standards and each object of that class has a sperate space in mem to store all it's members.

when a member is declared as static, all the objects of the class share this value and you can assign a value as static datatype data_var = some_value as you cannot do that in the constuctor as when an object is initialised this value will get overwriten.So we are allowed to do it within the class.

Helps?

p.s: look up on constructors

Actually,const can be changed.I donnt know about c++,but in c that should be true.

You don't HAVE to define NUM_TURNS as static. Defining it as static makes it common between all objects of that class. So if you have
GamePlayer a1;
GamePlayer a2;
then, a1.NUM_TURNS and a2.NUM_TURNS don't exist, but NUM_TURNS does.

thanks a lot

You don't HAVE to define NUM_TURNS as static. Defining it as static makes it common between all objects of that class. So if you have
GamePlayer a1;
GamePlayer a2;
then, a1.NUM_TURNS and a2.NUM_TURNS don't exist, but NUM_TURNS does.

True,and if NUM_TURNS were public you could access it by GamePlayer::NUM_TURNS

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.