mysql guy
mysql guy

Reputation: 245

one c++ syntax question (a structure method)

In the following code, what's the meaning of :next(next_par),info(info_par)?

struct list_node : public memory::SqlAlloc  
{ 
  list_node *next;  
  void *info;  
  list_node(void *info_par,list_node *next_par)  
    :next(next_par),info(info_par)   /* what's the meaning of :next(next_par),info(info_par)?*/
  {}  
  list_node()                    
  {  
    info= 0;  
    next= this;  
  }  
};  

looks like it wants to assign info_par to info for info(info_par), and assign next_par to next for next(next_par). But I didn't see the definition of next(), info().

Upvotes: 4

Views: 114

Answers (4)

Jason
Jason

Reputation: 32510

It's an initialization list that value-initializes the class or structure's member variables in the list. These variables are initialized before the actual body of the constructor itself is executed. Normally it's optional (although a good idea anyways since it creates a known-state for any member variables before the constructor body is executed), but it's also required if you are trying to initialize a base-class or structure without a default constructor from a derived class or structure since the base-class needs to be constructed before the derived class.

For instance:

struct base
{
    int a;
    base(int b): a(b) {}
};

struct derived: public base
{
    //we have to value-initialize the base-structure before the 
    //derived structure's construtor-body is executed
    derived(int c): base(c) {}
};

Upvotes: 1

Kik
Kik

Reputation: 428

That is the member initializer list, where you can initialize your members with direct calls to one of their constructors. In this case the next and info members are being initialized with the parameters sent to the list_node constructor.

Upvotes: 1

unwind
unwind

Reputation: 399803

This is a C++ initialization list. It only appears in constructors. It is used to assign values to data members of the object being constructed. The point is that once the constructor starts running, all data members are already given well-known values.

Upvotes: 1

GWW
GWW

Reputation: 44093

:next(next_par),info(info_par) is an initialization list for member variables. Instead of having:

list_node(void *info_par,list_node *next_par){
    next = next_par;
    info = info_par;
}

EDIT: Just as a note, initialization lists can be important if you have member object variables that need to be constructed with a non-default constructor.

Upvotes: 3

Related Questions