initialization of static variable inside a structure

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kiran280603
    New Member
    • Mar 2008
    • 1

    initialization of static variable inside a structure

    hi
    i have a class in which i have a structure.. how to initialize a static variable "var"

    Class A
    {

    struct start
    {
    static int var;
    };

    };

    actually when i am doing like
    A::start::var =1;
    its giving undefined reference error
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Static member variables are not part of any one struct variable. All the struct variables will use the same static variable. Therefore, the static variable has to be created outside the struct:
    [code=c]
    Class A
    {

    struct start
    {
    static int var;
    };

    };

    //in a .cpp ffile

    int A::start::var;
    [/code]

    Please note that in C++ class and struct are interchangeable . That is, if your members are declared as public/private/protected, there is no difference between a class and a struct. The single difference is when you do not specify public/private/protected, the default access for a class is private whereas the default access for a struct is public. Underneath it all, classes are implemented as structs.

    Comment

    Working...