14

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;
}
Community
  • 1
  • 1
Mars
  • 873
  • 1
  • 11
  • 24

3 Answers3

26

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;
Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
7

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 
Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
2

Static variables are saved in a different part of memory than any instance of a class. This is because they are not a PART of an instance of any class.

The code below compiles because the function t is never called.

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


    }
};

int main(int argc, char *argv[])
{
    qWarning() << "hi";
    TT * t = new TT();
    //t->t();
    return 0;
}

However, this code doesn't complie, because t is called

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

int main(int argc, char *argv[])
{
    qWarning() << "hi";
    TT * t = new TT();
    t->t();
    return 0;
}

You are allowed to have undefined references you don't use in C++ (and C for that matter). For some reason, I am unsure of, the compiler seems to think this code is referencing i, when the stuff above that complies was not referencing it until called (any ideas as to why)?

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

//int TT::i = 0;

void TT::t(){
    i=0;
}

Functional example, with the static defined:

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

int TT::i = 0;

void TT::t(){
    i=0;
}
David D
  • 1,571
  • 11
  • 12