Explain how static class member initialized?

Questions by anoop4real   answers by anoop4real

Showing Answers 1 - 30 of 30 Answers

sudha

  • Mar 26th, 2007
 

using Scope resolution operator.

 <class name>::<static var> =

Amit

  • Apr 9th, 2007
 

Static variables can not be initialized in a class as class is building block of the object and you can not allocate memory for class but of class object. Static variable needs to be initialized outside the class.

  Was this answer useful?  Yes

divya shukla

  • Jun 7th, 2007
 

Static class member initialized to zero when the first object of the class is created, no further initialisation is required.
for example
class text
{
};
void main()
{
   text t1.t2;   // (comment)here the first object is created so static class member initialised to zero.
}

  Was this answer useful?  Yes

Static members of a class are usually initialized outside the definition of class block.
Look at the following:

class static_member_class {
  public:
         static int i;
}

int static_member_class::i = 0;

In the above example static_member_class has a static member data 'i' of integer type. However the static member data is initialized out of the class definition withe class scope.

Here many people argue here that while initializing the static member specifying datatype (here 'int') is optional. In the above example we could have initialized the variable like

static_member_class::i=0;

and this is perfectly fine for any standard c++ compiler.
But specidying the datatype is required when we are declaring a static member data of any user defined type. In such situations we have to explicitly specify the user defined data type before initializing the static data.

Prasad2008

  • Jun 10th, 2008
 

static members can not be initialised within the class. Because what appears inside the class is just a declaration (note that declaring the static member within the class is mandatory, along with it you also have to define it separately outside the class). Static member has to be defined and initialised outside the class(if you wont initialise, its default value will be zero).

class sample{

static int a;

};
int sample::a=3;

OSaienni

  • Sep 12th, 2008
 

Everyone has forgotten, there is one type of class member that can be initialised within a class.

That's the constant integral data type.

eg.

class CInitialise
{
    static const int m_cInt = 10;

    static const char m_cChar = 's';

    static const long m_cLong = 1000000000;

     static const long long m_cLongLong = 2000000000000000;

};

Those all work.

yzesong

  • Jul 30th, 2009
 

Static variables of a class can only be initialized like this CLASS_NAME::STATIC_VAR_NAME = VAR_VALUE;


  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions