Initialization list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prashanth Kumar B R
    New Member
    • Jun 2007
    • 5

    Initialization list

    My companies C++ coding standard states that "Member initialization list should be used instead of assignment". I have a datamember that has to be initialized through a function call. Can I have function calls in initialization list.
  • keerthiramanarayan
    New Member
    • Nov 2007
    • 13

    #2
    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:

    [code="c++"]
    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::Test Class(void)
    :a(0),b(1),c(a+ b)
    {
    std::cout<<"a: "<<a<<" b: "<<b<<" c: "<<c<<std::endl ;
    }


    TestClass::Test Class(int a, int b)
    :a(a),b(b),c(ge tFunction())
    {
    std::cout<<"a: "<<a<<" b: "<<b<<" c: "<<c<<std::endl ;
    }

    TestClass::Test Class(int a, int b, int c)
    :a(a),c(instanc eGet()),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;
    }
    [/code]

    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

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Originally posted by keerthiramanara yan
      The order of execution of the function is not defined. This is compiler dependent.
      Not true.

      Member variables are initialized in the order they appear in the class declaration and not in the order of the initialization list.

      Comment

      Working...