125

Hi i am getting undefined reference error in the following code:

class Helloworld{
  public:
     static int x;
     void foo();
};
void Helloworld::foo(){
     Helloworld::x = 10;
};

I don't want a static foo() function. How can I access static variable of a class in non-static method of a class?

0

3 Answers 3

154

I don't want a static foo() function

Well, foo() is not static in your class, and you do not need to make it static in order to access static variables of your class.

What you need to do is simply to provide a definition for your static member variable:

class Helloworld {
  public:
     static int x;
     void foo();
};

int Helloworld::x = 0; // Or whatever is the most appropriate value
                       // for initializing x. Notice, that the
                       // initializer is not required: if absent,
                       // x will be zero-initialized.

void Helloworld::foo() {
     Helloworld::x = 10;
};
Sign up to request clarification or add additional context in comments.

5 Comments

thanks a lot man. I was instantiating HelloWorld::x but not with int. Once again thanks.
@AndyProwl I tried this and got a compiler error on the line that sets x to 0. It says 'foo' in 'class Helloworld' does not name a type. Any advice?
@ufmike semicolon at the end of foo() definition is causing the error.
Do I have to use Helloword:: x inside Helloworld::foo()? can I just use x?
@schantischul you don't need to qualify x with Helloworld.
80

The code is correct, but incomplete. The class Helloworld has a declaration of its static data member x, but there is no definition of that data member. Somehwere in your source code you need

int Helloworld::x;

or, if 0 isn't an appropriate initial value, add an initializer.

Comments

62

Old question, but;

Since c++17 you can declare static members inline and instantiate them inside the body of class without the need of an out-of-class definition:

class Helloworld{
  public:
     inline static int x = 10;
     void foo();
};

1 Comment

This also makes it significantly easier to initialize a private static variable (instance pointer) for a singleton class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.