I too had the same doubt. However I tried it out and it seemed to work fine. I made the following observations though. The order of execution of the function is not defined. This is compiler dependent. Next thing is that the function should generally not be a instance member function, since we cannot count on the object to be completely initialized.
Consider the following code:
-
class TestClass
-
{
-
public:
-
TestClass();
-
TestClass(int a, int b);
-
TestClass(int a, int b, int c);
-
-
private:
-
int a,b,c;
-
int instanceGet()
-
{
-
return a+b;
-
}
-
};
-
-
int getFunction()
-
{
-
return 1;
-
}
-
-
TestClass::TestClass(void)
-
:a(0),b(1),c(a+b)
-
{
-
std::cout<<"a: "<<a<<" b: "<<b<<" c: "<<c<<std::endl;
-
}
-
-
-
TestClass::TestClass(int a, int b)
-
:a(a),b(b),c(getFunction())
-
{
-
std::cout<<"a: "<<a<<" b: "<<b<<" c: "<<c<<std::endl;
-
}
-
-
TestClass::TestClass(int a, int b, int c)
-
:a(a),c(instanceGet()),b(b)
-
{
-
std::cout<<"a: "<<a<<" b: "<<b<<" c: "<<c<<std::endl;
-
-
}
-
-
int main()
-
{
-
TestClass c1;
-
TestClass c2(10,20);
-
TestClass c3(10,20,30);
-
return 0;
-
}
-
The order of evaluation of parameters is left to implementation. However the purpose of using initialization list is to directly give the value to a variable instead of doing an assignment. So calling a function in initialization list might not be so efficient