Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Static class members

Static class members

Scheduled Pinned Locked Moved C / C++ / MFC
question
13 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C csrss

    Ok, i just cannot get it. How can i nitialize static class members? I got such situation:

    class myClass
    {
    private:
    static myClass *pThis;
    public:
    .................
    };

    Now i am trying to initialize pThis to "this" so i can use it in some static methods, like threads and so. If i am trying to initialize it in constructor, compiler says that pThis is unresolved. Ok then, i am trying to initialize it to NULL outside a class, like this: myClass *myClass::pThis = NULL; Now linker says that pThis is already defined in myClass.obj. What am i doing wrong? Thanks

    011011010110000101100011011010000110100101101110 0110010101110011

    L Offline
    L Offline
    Luc Pattyn
    wrote on last edited by
    #2

    In C# one would use a "static constructor", which runs once, when the class gets referenced for the first time. However there is no such thing in C++, the best you can do is probably what is explained here[^]. :)

    Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum

    Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

    C 1 Reply Last reply
    0
    • L Luc Pattyn

      In C# one would use a "static constructor", which runs once, when the class gets referenced for the first time. However there is no such thing in C++, the best you can do is probably what is explained here[^]. :)

      Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum

      Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

      C Offline
      C Offline
      csrss
      wrote on last edited by
      #3

      Yeah, that issue appeared because i have this initializer in .h file, not in .cpp

      011011010110000101100011011010000110100101101110 0110010101110011

      1 Reply Last reply
      0
      • C csrss

        Ok, i just cannot get it. How can i nitialize static class members? I got such situation:

        class myClass
        {
        private:
        static myClass *pThis;
        public:
        .................
        };

        Now i am trying to initialize pThis to "this" so i can use it in some static methods, like threads and so. If i am trying to initialize it in constructor, compiler says that pThis is unresolved. Ok then, i am trying to initialize it to NULL outside a class, like this: myClass *myClass::pThis = NULL; Now linker says that pThis is already defined in myClass.obj. What am i doing wrong? Thanks

        011011010110000101100011011010000110100101101110 0110010101110011

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #4

        My previous message was incorrect; this works: In your header file you have the class definition so:

        class myClass
        {
        private:
        static myClass* pThis;
        public:
        myClass();
        // .................
        };

        in your implementation (.cpp) file you have:

        // static variables must be defined at file scope
        myClass* myClass::pThis;

        myClass::myClass()
        {
        // access to the class variable can be made in any method
        pThis = this;
        }

        The best things in life are not things.

        C 1 Reply Last reply
        0
        • C csrss

          Ok, i just cannot get it. How can i nitialize static class members? I got such situation:

          class myClass
          {
          private:
          static myClass *pThis;
          public:
          .................
          };

          Now i am trying to initialize pThis to "this" so i can use it in some static methods, like threads and so. If i am trying to initialize it in constructor, compiler says that pThis is unresolved. Ok then, i am trying to initialize it to NULL outside a class, like this: myClass *myClass::pThis = NULL; Now linker says that pThis is already defined in myClass.obj. What am i doing wrong? Thanks

          011011010110000101100011011010000110100101101110 0110010101110011

          N Offline
          N Offline
          Niklas L
          wrote on last edited by
          #5

          ..on the other hand, if you want to use it in thread functions it would be better to send it as a parameter to the thread function.

          C 1 Reply Last reply
          0
          • C csrss

            Ok, i just cannot get it. How can i nitialize static class members? I got such situation:

            class myClass
            {
            private:
            static myClass *pThis;
            public:
            .................
            };

            Now i am trying to initialize pThis to "this" so i can use it in some static methods, like threads and so. If i am trying to initialize it in constructor, compiler says that pThis is unresolved. Ok then, i am trying to initialize it to NULL outside a class, like this: myClass *myClass::pThis = NULL; Now linker says that pThis is already defined in myClass.obj. What am i doing wrong? Thanks

            011011010110000101100011011010000110100101101110 0110010101110011

            S Offline
            S Offline
            Stefan_Lang
            wrote on last edited by
            #6

            csrss wrote:

            so i can use it in some static methods

            If you want to use static member functions or access static variables in your class, you do not have to use a static pointer or instance of that class! When a member function is static, it means that it does not access any data members of the class or its base class(es), and also it does not use any member function that isn't also static. Therefore you do not need an instance of the class at all! Here is an example:

            class CMyClass {
            private:
            static int myMagicNumber; // defined static member variable here
            public:
            static void magic() { // defined a static method here
            std::cout << "My magic number is: " << myMagicNumber << std::endl;
            }
            };

            // initialize the static member variable in one of your cpp files like this:
            CMyClass::myMagicNumber = 111;

            int main() {
            // call your static method like this:
            CMyClass::magic(); // prints "My magic number is: 111"
            }

            As you can see I never created an instance anywhere; it isn't needed.

            C 1 Reply Last reply
            0
            • L Lost User

              My previous message was incorrect; this works: In your header file you have the class definition so:

              class myClass
              {
              private:
              static myClass* pThis;
              public:
              myClass();
              // .................
              };

              in your implementation (.cpp) file you have:

              // static variables must be defined at file scope
              myClass* myClass::pThis;

              myClass::myClass()
              {
              // access to the class variable can be made in any method
              pThis = this;
              }

              The best things in life are not things.

              C Offline
              C Offline
              csrss
              wrote on last edited by
              #7

              Yep, that is what i needed :)

              011011010110000101100011011010000110100101101110 0110010101110011

              1 Reply Last reply
              0
              • N Niklas L

                ..on the other hand, if you want to use it in thread functions it would be better to send it as a parameter to the thread function.

                C Offline
                C Offline
                csrss
                wrote on last edited by
                #8

                That is correct. Just wanted to avoid a lot of params and have one static instance for use everywhere ;)

                011011010110000101100011011010000110100101101110 0110010101110011

                S 1 Reply Last reply
                0
                • S Stefan_Lang

                  csrss wrote:

                  so i can use it in some static methods

                  If you want to use static member functions or access static variables in your class, you do not have to use a static pointer or instance of that class! When a member function is static, it means that it does not access any data members of the class or its base class(es), and also it does not use any member function that isn't also static. Therefore you do not need an instance of the class at all! Here is an example:

                  class CMyClass {
                  private:
                  static int myMagicNumber; // defined static member variable here
                  public:
                  static void magic() { // defined a static method here
                  std::cout << "My magic number is: " << myMagicNumber << std::endl;
                  }
                  };

                  // initialize the static member variable in one of your cpp files like this:
                  CMyClass::myMagicNumber = 111;

                  int main() {
                  // call your static method like this:
                  CMyClass::magic(); // prints "My magic number is: 111"
                  }

                  As you can see I never created an instance anywhere; it isn't needed.

                  C Offline
                  C Offline
                  csrss
                  wrote on last edited by
                  #9

                  How about such example:

                  DWORD __stdcall xxx::Monitor(LPVOID lParam)
                  {
                  HINSTANCE hExe = ::GetModuleHandle(NULL);
                  if (!hExe) hExe = ::LoadLibrary((LPCSTR)lParam);
                  if (!hExe) ::ExitThread(-1);
                  m_pThis->m_hMonitorHook =
                  ::SetWindowsHookEx (WH_MOUSE_LL, MsgMonitorStatic, hExe, 0);
                  if(m_pThis->m_hMonitorHook == NULL)
                  {
                  ::ExitThread(-1);
                  }
                  m_pThis->MonitorMessagePump();
                  UnhookWindowsHookEx(m_pThis->m_hMonitorHook);
                  return 0;
                  }
                  ....
                  m_hMonitorThread = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Monitor, whatever,
                  CREATE_SUSPENDED, &m_dwMonitorThreadId);

                  MsgMonitorStatic also uses m_pThis to access class members and functions, modify them, call them, check them? Here i gave small example, in my project there are hundreds of lines of a code of methods which call another methods.

                  011011010110000101100011011010000110100101101110 0110010101110011

                  S 1 Reply Last reply
                  0
                  • C csrss

                    How about such example:

                    DWORD __stdcall xxx::Monitor(LPVOID lParam)
                    {
                    HINSTANCE hExe = ::GetModuleHandle(NULL);
                    if (!hExe) hExe = ::LoadLibrary((LPCSTR)lParam);
                    if (!hExe) ::ExitThread(-1);
                    m_pThis->m_hMonitorHook =
                    ::SetWindowsHookEx (WH_MOUSE_LL, MsgMonitorStatic, hExe, 0);
                    if(m_pThis->m_hMonitorHook == NULL)
                    {
                    ::ExitThread(-1);
                    }
                    m_pThis->MonitorMessagePump();
                    UnhookWindowsHookEx(m_pThis->m_hMonitorHook);
                    return 0;
                    }
                    ....
                    m_hMonitorThread = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Monitor, whatever,
                    CREATE_SUSPENDED, &m_dwMonitorThreadId);

                    MsgMonitorStatic also uses m_pThis to access class members and functions, modify them, call them, check them? Here i gave small example, in my project there are hundreds of lines of a code of methods which call another methods.

                    011011010110000101100011011010000110100101101110 0110010101110011

                    S Offline
                    S Offline
                    Stefan_Lang
                    wrote on last edited by
                    #10

                    I can see no purpose the variable m_pThis serves, and I do not know why it is considered neccessary here. Nor do I see anything that's actually static. In fact, since you said that stuff is being modified, the member functions cannot be static. So I don't know why you think this is in any way relevant to your problem. The question is what do you want to achieve? As long as we don't know that we cannot advise you how best to implement it. P.S.: This is just a guess, but it's possible that in the code you've posted the pointer m_pThis is meant as a means to implement the 'Singleton' design pattern. If so, then this has nothing to do with the usage of static methods or static variables: static members require no instance at all, like in the code example I gave above, whereas a singleton requires exactly one instance. Also I am under the impression that such a construct isn't well suited to implement a singleton. But that is just an IMHO, and only a guess, since there is too little code to really get the picture.

                    modified on Monday, May 16, 2011 12:25 PM

                    1 Reply Last reply
                    0
                    • C csrss

                      That is correct. Just wanted to avoid a lot of params and have one static instance for use everywhere ;)

                      011011010110000101100011011010000110100101101110 0110010101110011

                      S Offline
                      S Offline
                      Stefan_Lang
                      wrote on last edited by
                      #11

                      Then my guess was right, your construct is indeed meant as a way to implement a singleton. This is wrong on so many accounts: 1. If you deal with multiple threads, this won't be thread safe 2. By making all your functions static, you give the false impression that these functions will not modify the internal state of your program, while in truth several effectively global parameters are being modified. Anyone else seeing and trying to use these functions may quite easily introduce fatal errors into the system. 3. Since your constructor creates the instance that you need, if that constructor is being called multiple times, your pointer will be overwritten, and you lose the current state of your application irrevokably. 4. Replacing function parameters with global variables is bad design. It will lead to functions producing different results with same parameters, making them effectively untestable.

                      C 1 Reply Last reply
                      0
                      • S Stefan_Lang

                        Then my guess was right, your construct is indeed meant as a way to implement a singleton. This is wrong on so many accounts: 1. If you deal with multiple threads, this won't be thread safe 2. By making all your functions static, you give the false impression that these functions will not modify the internal state of your program, while in truth several effectively global parameters are being modified. Anyone else seeing and trying to use these functions may quite easily introduce fatal errors into the system. 3. Since your constructor creates the instance that you need, if that constructor is being called multiple times, your pointer will be overwritten, and you lose the current state of your application irrevokably. 4. Replacing function parameters with global variables is bad design. It will lead to functions producing different results with same parameters, making them effectively untestable.

                        C Offline
                        C Offline
                        csrss
                        wrote on last edited by
                        #12

                        Stefan63, that is just wrong. Trust me i know what i am doing. One question: how would you implement custom control class by making it singleton while you need , lets say 10 instances of that class? you got 10 buttons on your dialog - now make this singleton. Second, have you ever heard of "static trampoline" ? Try this: encapsulate WndProc, CreateThread and SetWindowHookEx in a class - you will get idea. In case of mfc, encapsulating wndproc is actually out of the question, but that is not the point. Cheers

                        011011010110000101100011011010000110100101101110 0110010101110011

                        S 1 Reply Last reply
                        0
                        • C csrss

                          Stefan63, that is just wrong. Trust me i know what i am doing. One question: how would you implement custom control class by making it singleton while you need , lets say 10 instances of that class? you got 10 buttons on your dialog - now make this singleton. Second, have you ever heard of "static trampoline" ? Try this: encapsulate WndProc, CreateThread and SetWindowHookEx in a class - you will get idea. In case of mfc, encapsulating wndproc is actually out of the question, but that is not the point. Cheers

                          011011010110000101100011011010000110100101101110 0110010101110011

                          S Offline
                          S Offline
                          Stefan_Lang
                          wrote on last edited by
                          #13

                          Now what is it - in your previous post you stated you want one static instance, now you talk of multiple instances. You further stated that it's purpose is to save you the need to pass more parameters. And that I consider bad design. Therefore I'd not use a singleton to start with. Of course, if these premises are wrong, then this may invalidate my arguments. But if the solution provided above works for you, and you don't think my advice was helpful, then there's no point to continue the discussion.

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups