Because static member variables are not part of the individual objects, you must explicitly define the static member.
If you fail to initialize the static variable, Undefined Reference to staticVal will occur!
Example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
class Example {
public:
Example();
virtual ~Example();
protected:
static int staticVal;
};
#endif /* EXAMPLE_H_ */
Example.cpp
#include "Example.h"
#include <iostream>
int Example::staticVal = 3;
Example::Example() {
std::cout << staticVal << std::endl;
}
Main.cpp
#include "Example.h"
int main(int argc, char **argv) {
Example* ep = new Example();
}