Static Members

I'm attempting to create a logger class which has a static string vector. This way multiple instances of the logger can add strings to the same shared vector with out the need for pointers to a manager class or something like that..

Heres what I've got so far but I keep getting undefined reference errors:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Logger{
public:
    //Add String to Vector
    void Log(std::string theString) { mStrings.push_back(theString) }

    //Get String List
    std::string Get() {//Iterate through vector and return all strings as a single string..}

    //String Container
    static std::vector<std::string> mStrings;
};

class Test_A{
public:
    //Do stuff..
    void Foo() { mLogA.Log("Hello ") }

    //Logger instance
    Logger mLogA;
};

class Test_B{
public:
    //Do stuff..
    void Foo() { mLogB.Log("World") }

    //another Logger instance
    Logger mLogB;
};

int Main{
    //and another Logger Instance
    Logger mLogMain;    
    
    //Test Classes
    Test_A myClassA;
    Test_B myClassB;

    //Test Classes do your stuff..
    myClassA.Foo();
    myClassB.Foo();
    
    //output string
    std::string StringList;
    StringList = mLogMain.Get();

    //...String list should now contain "Hello World"
	
}


This is just an example really and probaly wont compile but thats essentially what I'm trying to do.
static member variables need to be defined outside the class definition. Try putting this after Logger's class definition:

std::vector<std::string> Logger::mStrings;

(And if you're going to put your code in multiple files, then the definition of Logger::mStrings should go in an implementation file)
Last edited on
Ah ok. Yeah I came across that solution elsewhere but I kept putting it in the header. Your advice worked perfectly. Thanks shaktar
Topic archived. No new replies allowed.