Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to static variable c++

Tags:

c++

static

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?

like image 597
Aqeel Raza Avatar asked Apr 29 '13 17:04

Aqeel Raza


Video Answer


1 Answers

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; }; 
like image 171
Andy Prowl Avatar answered Sep 27 '22 19:09

Andy Prowl