开发者

one c++ syntax question (a structure method)

开发者 https://www.devze.com 2023-03-11 22:13 出处:网络
In the following code, what\'s the meaning of :next(next_par),info(info_par)? struct list_node : public memory::SqlAlloc

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()                    
  {  
    开发者_Go百科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().


: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.


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.


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.


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) {}
};
0

精彩评论

暂无评论...
验证码 换一张
取 消