How can I make a single instance of this class without singleton and how can I declare it so another class can access it without declaring it globally?
Please read the codes (especially the comments) for a better understanding:
#include <iostream>
#include <vector>
// The only class that will be using this class is Obj...
// There can only be a single instance of ObjManager but how can I do that
// without singleton???
class ObjManager
{
friend class Obj;
int i;
};
// Since I cannot think of a better way of accessing the SAME and ONLY ObjManager, I
// have decided to declare a global instance of ObjManager so every instance of
// Obj can access it.
ObjManager g_ObjManager;
class Obj
{
friend class ObjManager;
public:
void Set(int i);
int Get();
};
void Obj::Set(int i) {
g_ObjManager.i += i;
};
int Obj::Get() {
return g_ObjManager.i;
};
int main() {
Obj first_obj, second_obj;
first_obj.Set(5);
std::cout << second_obj.Get() << std::endl; // Should be 5.
second_obj.Set(10);
std::cout << first_obj.Get() << std::endl; // Should be 15.
std::cin.get();
return 0;
};