0

I found a similar code like the one shown below, and two things confuse me. The first one, is it possible to have an object of the class, inside of the definition of the class, as in the example below in code 1? I though this was not possible, but maybe the static keyword is making this possible. Is this right? what is it actually happening here?

The second one, I learned that we can access static member variables and static member functions of a class just by calling the class name and the scope resolution operator (and the member we want). Apparently, the way described in code1 is an alternative manner of doing this. So, what is the main difference (or advantage) of doing it this way? In other words, what is the difference between code 1 and code 2?

//CODE 1
namespace LOGGER {
  class Logger;
}

class LOGGER::Logger {

    void foo(){}
  public:
    static Logger logger;
};

int main()
{
  LOGGER::Logger::logger.foo();
}





//CODE 2
namespace LOGGER {
  class Logger;
}

class LOGGER::Logger {
   public:
    static void foo(){}

};

int main()
{
  LOGGER::Logger::foo();
}
learning_dude
  • 1,030
  • 1
  • 5
  • 10
  • 1
    `static` variables are not part of any specific class instance. Normally `A` cannot contain an `A` because of recursion (make an `A` you have to make infinite `A`s). but with `static` there is exactly one `A::A` used by all `A`s. This looks like someone trying to make a singleton. [Here's a better singleton](https://stackoverflow.com/a/1008289/4581301). – user4581301 Mar 15 '20 at 17:54
  • hi, thanks...so the static will only allow a single instance, right? so, from that, we could be calling the other members of the class (no matter if they are public or private)? – learning_dude Mar 15 '20 at 18:01
  • Does this answer your question? [Static variables in C++](https://stackoverflow.com/questions/3698043/static-variables-in-c) – rsjaffe Mar 15 '20 at 19:18
  • A `static` member function is still a member, so it can access all `private` data and functions.But like a `static` member variable, the `static` function is not associated with a instance and can be invoked without an instance. `static` does not prevent multiple instances of the class, just that one member variable. There is only one `LOGGER::Logger::logger`, but nothing prevents creating another `LOGGER::Logger`. To prevent that, make the constructor `private`. [Some good documentation on `static`](https://en.cppreference.com/w/cpp/language/static) – user4581301 Mar 16 '20 at 02:23

0 Answers0