Static member variable

Aug 14, 2013 at 3:08pm
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 Aug 14, 2013 at 3:08pm
Aug 14, 2013 at 9:00pm
In *:
.h
1
2
3
4
class A {   
private:      
  static const string B;
};


In *.cpp:
const string A::B = "foo";
Aug 14, 2013 at 9:04pm
closed account (S6k9GNh0)
It could also be that A is a namespace.
Aug 14, 2013 at 9:05pm
@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.
Aug 14, 2013 at 9:28pm
@computerquip: The OP said
class A
.
@vlad from moscow: Did you read my post?
Aug 15, 2013 at 2:36am
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";
}
Aug 15, 2013 at 5:35am
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 Aug 15, 2013 at 5:36am
Aug 15, 2013 at 8:01am
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 Aug 15, 2013 at 8:02am
Topic archived. No new replies allowed.