How to initialize a static class variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rpm27
    New Member
    • Jan 2008
    • 23

    How to initialize a static class variable

    Hey everyone,

    I am trying to declare a static class variable (not a 'primitive' variable, but from a class i wrote) inside a class

    However, I have tried several ways to initialize it and they all caused compilation errors:

    Code:
    #include "MyClass.cpp"
    
    class A
    {
    static MyClass* m = new MyClass();
    
    public void example()
    {
    m->doSomething();
    }
    };
    The error that gives me is "request for member `doSomething' in `A::m', which is of non-class type `MyClass ()()'"

    I've also tried with the same result


    Code:
    #include "MyClass.cpp"
    
    class A
    {
    static MyClass m();
    
    public void example()
    {
    m.doSomething();
    }
    };
    Could someone direct me to what the solution is? Thank you
  • scruggsy
    New Member
    • Mar 2007
    • 147

    #2
    static members need to be initialized outside of the class definition (the only exception is for constant integers).
    Code:
    // Thingy.h
    
    class Thingy
    {
      static float someNum;
      ...
    };
    
    // Thingy.cpp
    
    float Thingy::someNum = 5.432;
    Your second example code there defines a static member function returning an object of type MyClass. I'm not sure what the compiler does with your first example.

    Comment

    • RRick
      Recognized Expert Contributor
      • Feb 2007
      • 463

      #3
      Be carefule of static class dependencies

      You can new an object for a static pointer value but you have to be careful of any dependencies between the classes.

      For example, assume you want two static classes newed (say A & B) and you expect A to be created before B. There is no guarantee which will be created first. This is especially troublesome if the newing is done in different source files (like A.cpp and B.cpp).

      Since you are dealing with static pointers to objects, it better to use the Singleton design pattern. This will allow you to get around the dependency issues. Here B can check and make sure that A is created first.

      Comment

      Working...