Trouble initilizing static variable.
Jun 28, 2021 at 4:00pm UTC
I am trying to initialize the variable count, which I declare in the class Count. However, I have tried doing it in multiple places in multiple ways and it does not work.
Main file:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include "Count.h"
using namespace std;
int main() {
// putting Count::count = 0; here doesn't work.
Count test1;
test1.information();
return 0;
}
Count.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include "Count.h"
Count::Count() {
// why can't I say count = 0; here?
// Count::count = 0; doesn't work either.
Count::count = 0;
}
Count::~Count() {
}
Count.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#ifndef COUNT_H_
#define COUNT_H_
#include <iostream>
using namespace std;
class Count {
public :
static int count;
public :
Count();
virtual ~Count();
void information(){
cout << count << endl;
};
private :
};
#endif /* COUNT_H_ */
Jun 28, 2021 at 4:12pm UTC
You need to initialize it globally in the cpp file for the class:
1 2
// near top of count.cpp, globally:
int Count::count = 0;
Jun 28, 2021 at 4:53pm UTC
or as C++17 just mark count as inline and set it's initial value.
As one file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
using namespace std;
class Count {
public :
inline static int count {};
public :
Count();
virtual ~Count();
void information() {
cout << count << '\n' ;
};
private :
};
Count::Count() { }
Count::~Count() { }
int main() {
Count test1;
test1.information();
Count::count = 11;
test1.information();
}
Jun 28, 2021 at 4:59pm UTC
Count::Count() {
// why can't I say count = 0; here?
// Count::count = 0; doesn't work either.
Count::count = 0;
}
Just to explain some reasoning here: static variables exist independently of any instance of the class. So the initialization of the variable can't rely on the constructor for a particular object being called.
Last edited on Jun 28, 2021 at 4:59pm UTC
Jun 28, 2021 at 5:00pm UTC
Thank you for your help.
Topic archived. No new replies allowed.