Globally available Class functions

Suppose I have something like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct C
{
    int number;
    void addOne(){number++;}
    C():a(0){}
}

struct B
{
};

struct A
{
    B b;
}


I'm trying to be able to instantiate 1 instance of C and any number of A and B. From there I want to be able to call C's addOne() function from inside of A or B and have it add 1 to the same variable "number" every time.

Is this possible to do without just re-writing the class as part of main()?
Last edited on
Looks like you want a singleton here. http://en.wikipedia.org/wiki/Singleton_pattern
Here is an example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class C
{
private
  static C* _self;
protected:
  C(){}
public:
  static C* Instance()
  {
    if(!_self) _self = new C();
    return _self;
  }
  void addOne(){number++;}
  int number; //left it public like in your code
};

//usage
C::Instance() -> addOne();

Or you can just make usage of static variables and do not create instances at all:
1
2
3
4
5
6
7
8
struct C
{
    static int number = 0;
    static void addOne(){number++;}
};

//usage
C::addOne();
Last edited on
I'll look into singletons.

I tried using static variables but ended up with some crazy linker errors.
Oh, I forgot about inability to assign non-const static variables in declaration
1
2
3
4
5
6
7
8
//C.h
struct C
{
    static int number;
    static void addOne(){number++;}
};
//C.cpp
int C::number = 0;
Topic archived. No new replies allowed.