| | |
A question about 'const'
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Aug 2004
Posts: 24
Reputation:
Solved Threads: 0
the book "Effective C++" have a item introduce cosnt,but a question i dont understand clearly.
why must define the NUM_TRUNS in static ?
C++ Syntax (Toggle Plain Text)
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 ?
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
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
•
•
•
•
Originally Posted by iamboredguy
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.
![]() |
Similar Threads
Other Threads in the C++ Forum
- Previous Thread: include file problem
- Next Thread: Faulty programme!!!
| Thread Tools | Search this Thread |
api array based beginner binary bitmap c++ c/c++ calculator char char* class code coding compile compiler console conversion count database delete deploy developer directshow dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelp homeworkhelper iamthwee ifstream input int java lib linkedlist linker list loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference rpg sorting string strings temperature template test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets





