Defining a constant datamember
Programe #1
// file.h
class File
{
public:
static const int var = 9;
};
-
// main.cpp
#include <iostream>
#include "file.h"
using namespace std;
int main() {
File f;
cout << f.var;
return 0;
}
Programe #2
// file.h
int Globalvar ;
class File
{
public:
static const int var = 9;
};
-
// main.cpp
extern int GlobalVar;
#include <iostream>
#include "file.h"
using namespace std;
int main() {
cout << GlobalVar;
return 0 ;
}
Program#1 is running fine, but program#2 gives linker error:
error LNK2005: "int GlobalVar" (?x@@3HA) already defined in file.obj
I know the header files are never compiled. Then in the above case, how the compiler knows the definition of variable var, but not able to find the definition of GlobalVar? What is the difference between this two programs?
Re: Defining a constant datamember
Quote:
Originally Posted by vikuseth
how the compiler knows the definition of variable var, but not able to find the definition of GlobalVar?
The compiler/linker was able to find the definition of GlobalVar. In fact, it found the definition at least twice: once in main.cpp, and another time in say, file.cpp. Hence the error message stated that the variable was "already defined in file.obj".
The solution is to define the variable in exactly one source file, and then put that extern declaration in the header instead.
In the case of the static const member variable, it is a special exception that you can initialise such a variable in the class definition if it is of an integer type. Otherwise, you should place the initialisation in exactly one source file.
Re: Defining a constant datamember
so shall i take like if it is a static const integral type of data then it can be defined inside .h file . It will not show any linker error . But for others it will show one error . Is it what you are saying ?
Re: Defining a constant datamember
Yes, that is the gist of what you're asking about, I think.