121

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?

1

3 Answers 3

152

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;
};
5
  • 4
    thanks a lot man. I was instantiating HelloWorld::x but not with int. Once again thanks.
    – Aqeel Raza
    Apr 29, 2013 at 17:35
  • @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
    Jul 14, 2016 at 20:06
  • @ufmike semicolon at the end of foo() definition is causing the error. May 2, 2021 at 20:40
  • Do I have to use Helloword:: x inside Helloworld::foo()? can I just use x? Jul 22, 2021 at 10:17
  • @schantischul you don't need to qualify x with Helloworld.
    – Hari
    Jun 8, 2022 at 11:53
78

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.

54

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
  • This also makes it significantly easier to initialize a private static variable (instance pointer) for a singleton class. Mar 9 at 20:33

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.