Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can non-static member function access static member function or data?

Tags:

c++

class

static

I searched the Internet and found that some people said that non-static member function can access static member function or data. Then I wrote a program to verify it.

#include <iostream>
class test
{
public:
    static int a;
    void printa()
    {
        std::cout<<a;
    }
};

int main(int argc, const char * argv[])
{
    test m;
    m.printa();

    return 0;
}

The code generate linker errors!

Undefined symbols for architecture x86_64:
  "test::a", referenced from:
      test::printa() in main.o
like image 905
user2261693 Avatar asked May 09 '13 06:05

user2261693


3 Answers

Declaring a variable as static inside a class is, well, only a declaration.

You need to define the variable as well, which means adding this line in a single compilation unit :

int test::a = 0;

To be more precise : a compilation unit is basically a .cpp file. You should not put that line directly in a header file, otherwise you will get the opposite error : "multiple definition of...".

This will also, as you have guessed, initialize your variable to 0 once your program starts.

If you put this line under your class declaration, it will fix your problem (in this specific situation : remember not to write this in a header file).

like image 81
Nbr44 Avatar answered Sep 25 '22 15:09

Nbr44


That's because you've only declared test::a, not defined it:

#include <iostream>
class test
{
    ...
};

int test::a = 1; //Needs a definition!
like image 38
Yuushi Avatar answered Sep 24 '22 15:09

Yuushi


You have only declared the static data member. You have not defined it.

YOu need to do something like int test:: a; to define it.

See this too

Non-static members are allowed to access static data members. The reverse is not allowed because static members do not belong to any object

like image 36
Suvarna Pattayil Avatar answered Sep 23 '22 15:09

Suvarna Pattayil