ashutosh
ashutosh

Reputation: 3

C++ static data members initialization in initialization list

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

Upvotes: 0

Views: 2416

Answers (3)

Tunvir Rahman Tusher
Tunvir Rahman Tusher

Reputation: 6631

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

Upvotes: 0

Tunvir Rahman Tusher
Tunvir Rahman Tusher

Reputation: 6631

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

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

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

Upvotes: 10

Related Questions