2

I have a Logger class in my C++ application. This class has public methods like writeDebug(std::string & str) , can write to a debug output file and it works for me very good. The object is being created on application start by the first main class and there it is stored as a Logger * myLogger; object.

Since I have other classes as well, I would like to provide this logging functionality to those classes as well.

Currently I oberhead the myLogger pointer to toher classes in their contructor, and all the other classes store this very same Logger pointer when being created --> all other classes has this Logger * myLogger pointer stored:

Other_XY_Class::Other_XY_Class(Logger * logger, ...) 
: localLoggerPtr{logger} { //.. }

==> localLoggerPtr (in class Other_XY_Class) == myLogger (in main application class)

I can imagine that there is a more convenient / elegant way to handle that ?

MarkZltr
  • 67
  • 2
  • 7
  • I would use a [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr) if you want one instance shared among many objects. – NathanOliver Aug 20 '15 at 12:38
  • Are you asking wheter using a *singleton* or a global variable is a better solution, for example? – Paolo M Aug 20 '15 at 12:41
  • You can think about making `Logger`s methods `static` – prajmus Aug 20 '15 at 12:45
  • I think what you do is called dependency injection and it is good. – trenki Aug 20 '15 at 12:45
  • @prajmus: I don't think making it static is good. That basically makes it a singleton. Why should I only want one logger? Maybe I want to have two different one to log to different files? – trenki Aug 20 '15 at 12:47
  • @trenki ok, I get the use case, but I just thought OP wants to have only one object, but doesn't want to share the pointer between classes. – prajmus Aug 20 '15 at 12:51
  • @trenki `Why should I only want one logger?` Because if you don't need more, then it's simpler. That said, I wouldn't make the memeber function static either. Instead, I'd use a global instance because that's just as simple and doesn't limit you to just one logger. – eerorika Aug 20 '15 at 12:51

1 Answers1

0

Since you only have one instance, why not use a Singleton for that?

Something along this lines:

class foo {
private:
   void bar();

   static foo Instance;

public:
  static void Bar() { Instance.bar(); }
}
MHolzmayr
  • 1,541
  • 1
  • 12
  • 22