MarcoS
MarcoS

Reputation: 160

static const in classes

I think is an old question but I don't get it.

I have a header routines.h, its functions file routines.cpp and the main file main.cpp.

In the header there is:

class myclass{
public:
static const double a;
void mymethod();
};

const double myclass::a=0.0;

The routines.cpp contains: #include"routines.h" and then define the methods.

main.cpp also has #include"routines.h".

This setup gives a link error: a it's already defined.

public: static double const myclass::a" (?a148@myclass@@2NB) already defined in DBFLOWPAR2.obj

DBFLOWPAR2 is my main file.

If I define the methods in routines.h it works fine, but I don't like that. What else it's possible? I don't care how the variables are defined, I just want to be able to access myclass.a and find the right value in it.

Upvotes: 3

Views: 720

Answers (4)

Robᵩ
Robᵩ

Reputation: 168626

You have violated the One Definition Rule. Because you #include "routines.h" in multiple files, the definition of myclass::a appears in multiple files.

You must define a variable once, and only once.

Choose a convenient .cpp file, and move your definition to that .cpp.

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258608

MyClass.h

class myclass{
public:
   static const double a;
   void mymethod();
};

MyClass.cpp

const double myclass::a;

The way you have it now, you're redefining myclass::a in every translation unit that includes the header.

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96258

Don't put const double myclass::a=0.0; in the header file, otherwise each compilation unit including this file will have it's own separate variable. put this to routines.cpp.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206526

You should define the static variable in a cpp file.
Move,

 const double myclass::a=0.0;

to your cpp file.

Defining a in header file creates a copy of the variable in each Translation Unit where the header is included.

Upvotes: 4

Related Questions