Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define static function outside the class and access static value .h and .cc files

Tags:

c++

class

static

 //foo.h
 class Foo 
  {
    private:
      static int number;

    public: 
      static int bar();
  };

//foo.cc
#include "foo.h"

 int Foo::bar() 
 {
   return Foo::number;
 }

this is not working. I want to define a static function outside the class definition and access a static value.

undefined reference to `Foo::number'
like image 786
thomas050903 Avatar asked Oct 26 '11 20:10

thomas050903


2 Answers

You just declared the static member you need to define it too. Add this in your cpp file.

int Foo::number = 0;

This should be a good read:

what is the difference between a definition and a declaration?

like image 86
Alok Save Avatar answered Sep 20 '22 20:09

Alok Save


you have to define Foo::number:

// foo.cc
...
int Foo::number(0);
like image 32
justin Avatar answered Sep 21 '22 20:09

justin