Optimizing Help Appreciated

Started by
11 comments, last by Zahlman 16 years, 10 months ago
Quote:This code gave me a couple of errors. I'd love to correct them but I cannot understand what

: Turn(1)

and

, Win(1)

do. If you can explain them to me I can go ahead and get rid of the errors and continue with the more "optimized" classes declaration.


The Win(1) should be Win(0), was too quick on typing.

What this does is same as the following:
class Gomoku{public:  Gomoku()  {    Turn = 1;    Win = 0;    InitializeGrid();    ShowGrid();  }


Which is the constructor. It'll be called whenever such object is constructed. As pointed out above, it initializes the variables.

This form:
class Gomoku{public:  Gomoku()    : Turn(1)    , Win(0)  {    InitializeGrid();    ShowGrid();  }

is the preferred syntax using initialization list.

Also, the fact that it's written inside the class definition has no special meaning here, it was just for compact form. You could write it like this:
class Gomoku{public:...  Gomoku();...};Gomoku::Gomoku()  : Turn(1)  , Win(0){  InitializeGrid();  ShowGrid();}


Quote:EDIT: Looking in the actual code I see someone added:

int Turn = 1;
int Win = 0;


Yes, copy paste error. Should be
int Turn;int Win;
Advertisement
The reason why you should use the : Object(data) in the constructor is because there is a difference between initialization and assignment.

consider this:
int a = 2; // 1
int b; // 2a
b = a; // 2b

Line 1 is initialization. Line 2a is also initialization, it just is created with a default value. The default value random junk in this case (although some compilers, in debug mode, initialize it to 0 it is not guaranteed). And line 2b is assignment.

Why does this matter? When you make your own objects. Lets say you created an object alpha which has a constructor like this:

class Alpha{  public:  Alpha(int initialize) : initialize(0) { }};


Then if you made object beta contain an instance of beta, you Have to initialize it because there is no default constructor. That is to say, this won't compile:
class Beta{  Alpha value;  public:  Beta() { }};
because by the time the code execution gets to the block ( {} ) all constructors have been called. From now on you can only assign to to the objects. The way c++ gets around this is by using the 'initialization list' described by Antheus. Hope that helps.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

Thanks, guys, for covering the initialization list stuff. Hopefully our OP can take the next step now along the lines I was hoping for [wink]

(Just to be clear, the code provided with an initialization list was Antheus' rather than mine. I was hoping to just get the OP to put the relevant members into the class first, and then I could explain about constructors and initialization lists...)

This topic is closed to new replies.

Advertisement