Bascy Bascy - 12 days ago 5
C++ Question

Refering to static member of a class result in "not a static member of class"

I'm an experienced programmer, but really new on c++ .. so please bear with me

I want to create a class were classes are derived from when they use a certain feature of the program that has to be initialized only once.
I created the class with a static bool member, and a default constructor. The default constructor checks the static member and runs the initialization if needed:

class WireUser {
public:
static bool wireIntialized;
WireUser::WireUser();
};

bool WireUser::wireInitialized = false;

WireUser::WireUser() {
if (!wireInitialized) {
Wire.begin();
wireInitialized = true;
}
};


When i try to compile this i get the following error:


error: 'bool WireUser::wireInitialized' is not a static member of 'class WireUser'
bool WireUser::wireInitialized = false;


If i remove the line were the member is initialized as false, the same errors occurs on the line containing
if (!wireInitialized) {


I don't understand what i'm doing wrong.
Can anybody help?

Answer

There's a number of typos and small errors/warnings in your code (steps for fixing explained in the comments):

class WireUser {
public:
  static bool wireInitialized;
  WireUser(); // Don't use scope specifiers in declarations:  WireUser::WireUser();
};

bool WireUser::wireInitialized = false; // Typo fixed here 'wireInitialized' isn't the 
                                        // same as         'wireIntialized'

WireUser::WireUser() {
  if (!wireInitialized) {
    // Wire.begin(); Commented out because it's not in context of your question
    wireInitialized = true;
  }
} //; <<<< Omit the semicolon to get rid of the warning

int main (){
    WireUser wu;
    return 0;
}

Live Demo.


Also you should consider to make that thread safe for initialization.
A std::atomic<bool> might be the right choice:

#include <atomic>

class WireUser {
public:
  static std::atomic<bool> wireInitialized;
  WireUser();
};

std::atomic<bool> WireUser::wireInitialized = {false};

WireUser::WireUser() {
  if (!wireInitialized) {
    // Wire.begin();
    wireInitialized = true;
  }
}

int main (){
    WireUser wu;
    return 0;
}

Live Demo

Comments