unusual constructor syntax

Hi All,

I read a code recently and came across a constructor syntax which I can't understand.

Here is the code snippet:

//class ArbPulses is derived from class RF_Pulse
class ArbPulses: public RF_Pulse
{
public:
ArbPulses();
~ArbPulses();
protected:
long m_lNumPointsX;
long m_lNumPointsY;
}

//Constructor
ArbPulses::ArbPulses()
: RF_Pulse,
m_lNumPointsX,
m_lNumPointsY
{

};

I can't understand syntax of this constructor. Why member variables m_lNumPointsX and m_lNumPointsY are written outside the braces of constructor.

Can someone please explain it ?

Thank you.


It's an initializer list:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html

EDIT:
here's an example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// initializer list used to initialize a reference
class CC
{
public:
int &a;


CC(int &_a) :a(_a) // initialize  a  using initializer list
  {
    // a=_a; // //uncommenting this line causes a compilation error
  }
void print()
  {
    cout <<a<<" ";
  }

};



int main()
{
int i=10; 
CC cc(i);

cc.print(); // print 10
i=11;       // i has changed so cc.a must change its value too
cc.print(); // print 11

getchar();
}
Last edited on
It's called an initializer list. It lets you call specific constructors for your class's parents and members.

For example let's say you have this parent class:

1
2
3
4
5
6
7
8
class Parent
{
public:
  Parent(int foo)
  {
    // we want our child class to call this ctor
  }
};


How would we have our child call this ctor?

1
2
3
4
5
6
7
8
9
class Child : public Parent
{
public:
  Child()
  {
    // 'Parent' has already been constructed by the time this code executes, so it's too late
    //   to pick a ctor
  }
};


The solution is to use an initializer list:

1
2
3
4
5
6
7
8
9
class Child : public Parent
{
public:
  Child()
    : Parent(5)  // select which ctor to use
  {
    // now 'Parent' has been constructed with the proper ctor
  }
};


You can also do this with members of the class.

However in the particular code you posted, it looks like the default ctors are used, which is completely pointless because those would be used even if you left out the initializer list.

EDIT: doh, too slow
Last edited on
Thanks a lot for your replies.. !
Topic archived. No new replies allowed.