Question

I am new to C++ and I am trying to learn the different uses of static keyword, I read that one of them is to define a static variable inside a class and call it using the scope operator. I tried to used that but Visual Studio 2012 produce an linking error. My code is:

class Vehicle
{
public:
    Vehicle(){};
    ~Vehicle(){};
    static int temp;
};

int _tmain(int argc, _TCHAR* argv[])
{

    Vehicle::temp=100;

    std::cout << Vehicle::temp << std::endl;

    system("Pause");
    return 0;
}

And the error is:

1>LearningC++.obj : error LNK2001: unresolved external symbol "public: static int Vehicle::temp" (?temp@Vehicle@@2HA)

1>c:\users\avraam\documents\visual studio 2012\Projects\LearningC++\Debug\LearningC++.exe : fatal error LNK1120: 1 unresolved externals

What may cause this problem?

Edit1 (to make it more clear):

My question is how can I access a static variable declared inside a class? Is this possible without using a member function?

Was it helpful?

Solution

You need to define temp, add this after class Vechicle:

class Vehicle
{
// Left out class code for brevity
   void useTemp() { temp = 200 ; } // Adding method inside class the uses temp
};

int Vehicle::temp = 0 ;

Note, you do not need static keyword when you define temp. Since it is static you do not need an instance of the class to access the variable, so the code you had in main is correct:

Vehicle::temp=100;

std::cout << Vehicle::temp << std::endl;

Vehicle v1 ;
v1.useTemp() ;

std::cout << Vehicle::temp << std::endl;

OTHER TIPS

You need to define the static member outside the class:

#include <iostream>

class Vehicle
{
  public:
     Vehicle(){};
    ~Vehicle(){};
    static int temp;
};

int Vehicle::temp = 0; 

int _tmain(int argc, TCHAR* argv[])
{
    Vehicle::temp = 100;  //^^access the variable with classname plus ::
    std::cout << Vehicle::temp << std::endl;
    std::cin.get();
    return 0;
}

then access it in main with classname followed by :: and variable name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top