I want to share an instance of a class globally so that I can access a member function of the class from whatever source file I want. I'm sort of new to this, so I'm wondering about the best way to go about it. For the record, this is for a part of my program that will output text to a log window, so the input will be coming from pretty much every single class in my program. Here's some sample code:
MyClass.h
class MyClass
{
public:
  MyClass();
private:
  int start, end;
  void parse(std::string);
};
MyClass.cpp
#include "myclass.h"    
MyClass::MyClass()
{
}
void MyClass::parse(std::string){
// do some stuff here
}
OtherClass1.h
#include "myclass.h"    
class OtherClass1
{
  public:
    OtherClass1();
  private:
    MyClass someInstance1;
};
OtherClass1.cpp
#include "otherclass1.h"
OtherClass1::OtherClass1()
{
  someInstance1.parse("This is a string.")
}
Ok, great. But now I want to be able to use that same someInstance1 instance in yet ANOTHER class (i.e. OtherClass2). I don't want to have to create a MyClass someInstance2 in OtherClass2. How do I use the someInstance1 located in OtherClass1 that I have already created?
Here's what I have for OtherClass2. I can't use someInstance1 because it is private.
OtherClass2.h
#include "myclass.h"
#include "otherclass1.h" 
class OtherClass2
{
  public:
    OtherClass2();
  private:
    MyClass someInstance2;
};
OtherClass2.cpp
#include "otherclass2.h"
OtherClass2::OtherClass2()
{
  someInstance2.parse("This is a string.")
}
I only want one instance of MyClass throughout my entire program. Is there a better way to do this? I always read that having global anything is bad practice, but how else should I go about it?
EDIT: I wound up following the answer here: https://stackoverflow.com/a/2798624/2574608
 
     
    