Static member variable

If I have defined this in my *.cpp file
 
  const string A::B = "foo";

does it mean that I have to define variable B as static member of class A in my *.h file?
Last edited on
In *:
.h
1
2
3
4
class A {   
private:      
  static const string B;
};


In *.cpp:
const string A::B = "foo";
closed account (S6k9GNh0)
It could also be that A is a namespace.
@Slazer

If I have defined this in my *.cpp file



const string A::B = "foo";


does it mean that I have to define variable B as static member of class A in my *.h file?


static data members are declared in class definitions.
@computerquip: The OP said
class A
.
@vlad from moscow: Did you read my post?
Well, I just tested it without the static storage class and it seems to work fine. Sooo does that answer your question?
*.h:
1
2
3
4
5
6
7
class AnotherTest
{
private:
  const std::string B;
  AnotherTest();
  ~AnotherTest();
};

*.cpp:
1
2
3
4
5
6
#include "AnotherTest.h"
#include <string>
AnotherTest::AnotherTest()
{
const std::string  B = "stuff";
}
Variable B defined as a data member in the class

1
2
3
4
5
6
7
class AnotherTest
{
private:
  const std::string B;
  AnotherTest();
  ~AnotherTest();
};


and local variable B defined inside the constructor

1
2
3
4
5
6
#include "AnotherTest.h"
#include <string>
AnotherTest::AnotherTest()
{
const std::string  B = "stuff";
}


are two different objects. Data member B is an empty constant string that have storage duration until an object of the class exists. Local variable B inside the constructor has automatic storage duration and is destroyed after the constructor will finish his work.

Last edited on
Const data member has to be initialized in the constructor. Each instance of A will have their own B (so each A::B can hold a different value).

If the implementation defines const string A::B = "foo";, then A::B is initialized exactly once, not in constructor, and it will be initialized even if no A is ever created within the program. Therefore, yes, A::B is/should/must be a static member variable.

Static member variable is like a global variable, but has the benefit of being accessible only by those, who can access members of A.
Last edited on
Topic archived. No new replies allowed.