Before using static members I've to initialize them like in this Example.
I would like to do same in my code. But it does not work.
GCC is telling me:
undefined reference to MainClass::TheStatic1
Code:
#include <iostream>
using namespace std;
The base class constructor inits 'a' with given Argument
class MyStaticBase {
public:
MyStaticBase(int iSetA):a(iSetA){};
~MyStaticBase(){}
int a;
void SayHello(){
std::cout << "Say Hello from Static Instance: " << a << std::endl;
}
};
Derived classes init the the Base class with their specific values.
// First derived Class
class MyStaticDerived1:public MyStaticBase{
public:
MyStaticDerived1():MyStaticBase(1){ }
};
// Second derived Class
class MyStaticDerived2:public MyStaticBase{
public:
MyStaticDerived2():MyStaticBase(2){}
};
Containing two similar Members, only difference is the constructor call, when they are derived from their base class.
class MainClass {
public:
MainClass(){};
~MainClass(){};
static MyStaticDerived1 TheStatic1;
static MyStaticDerived2 TheStatic2;
};
The Main
int main() {
MainClass TheMainClass;
// [PROBLEM]: gcc:undefined reference to `MainClass::TheStatic1'
TheMainClass.TheStatic1.SayHello();
TheMainClass.TheStatic2.SayHello();
}
Attempts in main() to solve ( jap, some of them are just guessing )
// Attempts:
// MyStaticDerived1::MyStaticDerived1(); // error: cannot call constructor ‘MyStaticDerived1::MyStaticDerived1’ directly [-fpermissive]
// MainClass::TheStatic1 TheStatic1; //error: expected ‘;’ before ‘TheStatic1’
// MainClass::TheStatic2 TheStatic2 = 0;
// MainClass::TheStatic1();
// MyStaticDerived1 MainClass::TheStatic1; //qualified-id in declaration before ‘;’ token
// MyStaticDerived1 MainClass::TheStatic1{}; //qualified-id in declaration before ‘{’ token
Why I'm doing this?
MyStaticDerived are thread handling classes which are called by a signal Handler (SIGCHILD). This handler can only access static Members. Two groups of processes are managed, so I need two similar threadhandling classes.
Copy paste code for working example. Thx to @ThomasMatthews and @user4581301 for making this answer possible. See the solution above the main function. Futur informations please find in the links provided by @ThomasMatthews.