0

How can I access a1, and a2 from c1::c2::func?

class c1
{
    public:
    class c2
    {
        protected:
        static void func();
    };

    public:
    static int a1;
    private:
    static int a2;
};



void c1::c2::func()
{
    int f1= c1::a1; //works
    int f2= c1::a2;

    c1::a1= 1;  //fails
    c1::a2= 2;

    printf("func"); 
}

error:

prog.cpp:(.text+0xc): undefined reference to c1::a1' prog.cpp:(.text+0x16): undefined reference toc1::a2'

http://ideone.com/nK75A6

mrgloom
  • 20,061
  • 36
  • 171
  • 301

1 Answers1

1

The code will be compiled successfully if you define the static data members.

int c1::a1;
int c1::a2;

As it seems that the compiler does not generate object code for statements

int f1= c1::a1; //works
int f2= c1::a2;

because variables f1 and f2 are not used then it does not bother that a1 and a2 were not yet defined.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Ok, I unerstand this but why int f1= c1::a1; int f2= c1::a2; works without definition? or this is problem of ideon compiler? – mrgloom May 29 '14 at 11:06
  • @mrgloom It is because variables f1 and f2 are not used. So it seems that the compiler simply does not generate the object code for these two lines. – Vlad from Moscow May 29 '14 at 11:08
  • last question: what if c1::a1 not static can I access it from c1:c2::func? – mrgloom May 29 '14 at 11:23
  • @mrgloom Yes the function can access private data members of the enclosing class. However they can be accessed using an object of the enclosing class. – Vlad from Moscow May 29 '14 at 11:27