about ===struct=== in C++

Started by
3 comments, last by Chalit 21 years, 6 months ago
I found somthing in DX SDK about struct this struct SFrame { UINT iCount; SFrame() //=====> This is my first problem : iCount(0) //====> This is my second problem { } } 1.In standard c++ struct can have constructor or specially MS VC++ 2. :iCount(0)--->What it mean? Why don''t put in constructor ? thank for every ans.
Advertisement
constructor : member( value ){}

means that when the constructor is called, the member will be set to the value. I think that its standard C++.
i just learned this recently so i''ll share

structs and classes are exactly (structure-wise) except classes are private by default and structs are public

Beginner in Game Development?  Read here. And read here.

 

In C++, a struct is the same as the class except for default visibility - stuff starts private if you have a class but is public if you use a struct. That''s all.

As for the other stuff, that''s an initialization list. This is simply initialising member variables. You *could* initialise them in the constructor''s body butan initialisation must be used for some other things (like passing arguments to base constructors, if necessary). It''s a good habit to use the initialisation list - the only problem is if one variable depends on another. Variables get initialised based on the order they appear in the class'' prototype (from top to bottom, IIRC).

If you have several variables relying on each other then that could cause problems, in which case you might consider initialising them in the normal way inside the constructor body.

The syntax is simply
constructor_name(): var_a(21), var_b(22)
{
//constructor body
}

Where var_a and var_b would be member variables initialised to 21 and 22 respectively.
Oh, and to show what I mean about the order of initialisation, try this...


  #include <cstdlib>#include <iostream>using namespace std;class Test{public:  int a;  int b;    Test(): b(21), a(b)  {    cout << a << " and b is " << b << endl;  }};int main(int argc, char *argv[]){  Test mytest;    system("PAUSE");	  return 0;}  

Notice the constructor: "Test(): b(21), a(b)"

You might think that b would get initialised to 21 then a would be assigned the same value as b (21). However, the initialisation depends on the order that they''re declared - in this case, a is initialised first (to an unknown value, because b hasn''t been initialised)! B is then assigned a value. This problem can be very nasty if you use new() on variables, so I tend to do that work inside constructors.

This topic is closed to new replies.

Advertisement