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;
}
// 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();
}
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.