Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ member function access private static variable? [duplicate]

Possible Duplicate:
What does it mean to have an undefined reference to a static member?

I don't know why I got error "undefined reference to `TT::i'" if I implement the function outside of class declaration? Here is the code..

class TT{
private:
    static int i;
public:
    void t();
};

void TT::t(){
    i=0;
}
like image 765
Mars Avatar asked Mar 23 '12 04:03

Mars


Video Answer


2 Answers

undefined reference to `TT::i'

is because you havent defined the static data member outside class. All static data members have to be defined outside class before using them.

class TT
{
private:
    static int i;
public:
    void t();
};

void TT::t()
{
    i=0;
}
int TT::i=0; // define it outside the class. and if possible initialize 
like image 116
Rohit Vipin Mathews Avatar answered Sep 20 '22 04:09

Rohit Vipin Mathews


It's nothing to do with where you defined the function, it's that you didn't define the static member variable, you only declared it. You need to put its definition outside the class, e.g.

int TT::i;
like image 21
Stuart Golodetz Avatar answered Sep 22 '22 04:09

Stuart Golodetz