I was wondering if (in C++) you can instantiate a class (class foo) then have said class return the already instantiated object. (foo::instance())
In other words, can I have a class return it’s-self via it’s own methods? I want to be able to create a class (i.e. class foo) early in my program so it is already setup and ready to go. Then, farther down the line, I want to be able to call functions from that class without having to pass that object as an argument to my calling function. Can I do something like so:
MyClass::ReturnSelf()->foo();
or
MyClass::ReturnSelf().foo();
EDIT: I just realized this might be a little unclear. I want to be able to have another class call this “self-returning” method so it can use the already instantiated object’s methods and members without creating a new object.
Congrats, you’ve discovered the singleton pattern. Quite a caveat, if you didn’t already know it.
and call the method as:
Of course, you could also make the method
static, if that’s an option, and call it directly:The effect of returning the instance from methods can also be used for method chaining: