-1

I fail to understand as why I get LNK1120: Unresolved externals and LNK2001: Unresolved external symbol error messages for the following code in C++

class base
{
public:
    static int x;
    void fun()
    {
       base::x = 10;
       cout << base::x;
    }
};

int main()
{
    base b;
    b.fun();
    return 0;
}
Aniruddha
  • 837
  • 3
  • 13
  • 37

2 Answers2

1

When you declare a static member in a class, you have to also provide a definition outside the class declaration; like this:

class base
{
public:
    static int x; // DECLARES the variable
    void fun()
    {
       x = 10; // You don't need the base:: prefix inside the class!
       cout << x;
    }
};
int base::x = 0; // DEFINES the variable
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

You have only declared x inside the class. Since it's a static variable you must allocat it's memory outside the class scope.

Just add: base::x = 0; After you close the base class.