Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "undefined reference" compiler error

Tags:

c++

oop

find a bug in following code :

class A
{
   public:
    static int i;
    void print()
    {
      cout<< i << endl ;
    }
 };

 int main()
 {
    A a;
    a.print();
  }

I run above code, and I am getting "undefined reference to `A::i'" . Why I am getting this error ?

like image 753
siva Avatar asked Dec 01 '22 04:12

siva


1 Answers

Since A::i is a static member, it has to be defined outside of the class:

using namespace std;

class A
{
public:
    static int i;  // A::i is declared here.

    void print()
    {
        cout << i << endl;
    }
};

int A::i = 42;     // A::i is defined here.
like image 105
Frédéric Hamidi Avatar answered Dec 04 '22 13:12

Frédéric Hamidi