954,141 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

A question about 'const'

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 ?

XianBin
Newbie Poster
24 posts since Aug 2004
Reputation Points: 15
Solved Threads: 0
 

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

FireNet
Posting Whiz in Training
258 posts since May 2004
Reputation Points: 108
Solved Threads: 7
 

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

GDFans
Newbie Poster
4 posts since Sep 2004
Reputation Points: 11
Solved Threads: 0
 

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.

iamboredguy
Newbie Poster
23 posts since Aug 2004
Reputation Points: 12
Solved Threads: 0
 

thanks a lot

XianBin
Newbie Poster
24 posts since Aug 2004
Reputation Points: 15
Solved Threads: 0
 
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

FireNet
Posting Whiz in Training
258 posts since May 2004
Reputation Points: 108
Solved Threads: 7
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You