0

Why can't static data members initialized in an constructor's initialization list while it can be done in the constructor's definition ?

1
  • 1
    How do you propose you initialize a data member in the constructor's body? Commented Apr 10, 2013 at 5:35

3 Answers 3

10

You got it wrong. They can be initialized in a single translation unit outside the class definition* and they can be assigned to in the constructor.

You can only initialize current non-static class member in the initialization list of the constructor.

*Exceptions apply

Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer (+1). Congrats on the 100k!
thnx for the clarification
0

Static members are in class scope i.e they are class variable not instance variable.We initialize instances by constructor. As static variable are not for the instance but for the entire class so static variables are not initialized by constructor . Thanks

Comments

0

Lets try this more specific

#include <iostream>

using namespace std;

class classWithStaticVariable
{

    static int aStaticVariable;

    int aNormalInstanceVariable;
public:
    classWithStaticVariable(int aParameter)
    {

        aNormalInstanceVariable=aParameter;

        aStaticVariable=aNormalInstanceVariable;/////It is possible to assign value to static data member in constructor but not possible to init it.

    }

    void aTestFunctionJustToPrint()
    {


        cout<<aStaticVariable<<aNormalInstanceVariable;
    }



};
int classWithStaticVariable::aStaticVariable=1;

int main()
{

    classWithStaticVariable t(2);

    t.aTestFunctionJustToPrint();


}

Static variable are class variable not instance variable. So these static variable must be initialized with the class definition. Again constructor is used to initialize the instance variable for an object when it is created.Thats all. Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.