How to have a class return an instance of it's-self.

Hi guys,
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();
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.
foo anInstance;

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.
anInstance.someClassFunction();

Is this not just how a class is normally used? Have I misunderstood your question?
Last edited on
How will you know which instance of the class you are calling the functions on?

Or is it a singleton class?

In which case the singleton or monostate pattern might be appropriate
Well yes he is talking about a singleton class.

The singleton pattern, basically has a private member variable of the same type as the class and also hides its constructor(s) and destructor from the outside, so these too go in the private section of the class (or protected if you need to inherit from this class). Finally, you implement a public static method to get the single instance of this class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class CFoo
{
public:

   static CFoo* get_instance()
   {
      if (!m_pInstance)
         m_pInstance = new CFoo();
         
      return m_pInstance;
   }

   static void delete_instance()
   {
      if (m_pInstance)
      {
         delete m_pInstance;
         m_pInstance = NULL;
      }
   }
   
private:
   CFoo() 
   {
   }
   
   virtual ~CFoo()
   {
   }
   
   static CFoo* m_pInstance;
};


Hope that helps.
Last edited on
@mik2718 @ajh32: Are you serious ? It's obvious he isn't talking about a singleton.
A singleton has nothing to do with creating/returning an instance of the class. It guarantees that the instance will be unique. That's a totally different problem.

@snow 56767: As Moschops said, what you describe is just how a class is normally used in C++;
1
2
MyClass MyObject(/* optional arguments here */); // create an instance of MyClass
MyObject.foo(); 
closed account (zb0S216C)
I think the OP is trying to refer to a factory class[1, factory].

References:
[1, factory] http://en.wikipedia.org/wiki/Factory_method_pattern


Wazzak
Last edited on
The examples given at the end of the opening post do look like singleton usage?

As written above:

MyClass::ReturnSelf()->foo();
or
MyClass::ReturnSelf().foo();

If ReturnSelf() returned a new instance of the class each time, there would be no persistence of state.

And the comment about:

I want to be able to call functions from that class without having to pass that object as an argument to my calling function.

Makes me think they mean something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
using namespace std;

class MyClass {
public:
    static MyClass& ReturnSelf();

    const string& getMsg() const {
        return m_msg;
    }

    void setMsg(const string& msg) {
        m_msg = msg;
    }

private:
    MyClass(){}

    string m_msg;
};

MyClass& MyClass::ReturnSelf() {
    static MyClass s_myClass;
    return s_myClass;
}

void prepMsg(const char* text) {
    MyClass::ReturnSelf().setMsg(text);
}

void dispMsg() {
    cout << MyClass::ReturnSelf().getMsg() << "\n";
}

int main() {
    prepMsg("Hello world!");
    dispMsg();
    return 0;
}


Andy
Last edited on
Well, I can get my code to compile now. But, my instance returning method returns a new instance every time it is called and I don't want that. I need there to be one and ONLY one instance of the class during the lifetime of the application and I need to be able to return said instance. And the reason I can't just say, declare class Foo as global then use it that way the class is used through-out the code. It is also a bad practice to have global variables unless necessary and the new and delete operators are too slow for what I'm doing. So what I need is a class that returns a single initialized instance of it's-self via a static method. That way the members are persistent between calls and the class is only ever initialized once. I believe this means I need a Singleton class, but I'm not sure.
closed account (D80DSL3A)
While I don't feel that I know enough about design patterns to make a recommendation here, I can contribute a link to where many patterns are classified and presented:
http://sourcemaking.com/design_patterns
There are two patterns which basically achieve the same thing: singleton and monostate

I like the monostate pattern, usage of the pattern in code looks more natural

http://c2.com/cgi/wiki?MonostatePattern

In the monostate pattern all the data is static but the methods are not, when you make a new instance of the class you actually get a new instance, but it is gauranteed to be the same as all the other instances because of the all-static data

Here is what it looks like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// in header
class MyMonostate
{
private:
  static mycomplexdata* data;
  static bool initialised;
  void initialise();
public:
  MyMonostate(); // get an "instance"
  ...
  // other methods
  ...
};

// in cpp file
// define initial static data values
mycomplexdata* MyMonostate::data = NULL;
bool MyMonostate::initialised = false;

void initialise()
{
// set up complex data here
  ...
// at end of this function
  initialised = true;
}

// constructor, calls initialise the first time only
MyMonostate::MyMonostate()
{
  if(initialised)
    return;
  initialise();
}


Whenever you want to use the class you just create one, and start using it. The first time you do this the initialise() method will be called, it will not be called again.

both monostate and singleton can have problems when multithreading is used

@mik2718:

Thanks for posting the Monostate pattern. I haven't seen that before, but on first glance it looks vastly preferable to singletons. Traditional singletons are, frankly, vile, especially if you're working in a Test-Driven Development environment. I understand that it's convenient to be able to pull an instance with a persistent state out of the ether at any point in your code, but it introduces so much coupling and other annoying complications that I would recommend against using them to pretty much anyone.

This monostate pattern looks like a much better alternative.
I was able to get it to work. It was easy to use a Singleton because I only need bare bones and so this worked just fine:

Foo.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Some hypothetical class
class CFoo
{
public:
    CFoo();
    CFoo(const CFoo&);
    ~CFoo();

    CFoo operator=(const CFoo&);

    static GetInstance();

private:
    static CFoo mInstance;
};


Foo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static CFoo::mInstance;

CFoo::CFoo() {}

CFoo::CFoo(const CFoo&) {}

CFoo::~CFoo() {}

CFoo CFoo::operator=(const CFoo&)
{
   return *this;
}

static CFoo CFoo::GetInstance()
{
   return mInstance;
}
@OP: ¿do you understand why global are evil?
¿do you realize that singleton have the same issues?
The global scope isn't bad. It is used in professional code all the time. You just need to use it responsibly.

Also, my code is wrong, I need to be returning a reference to the class like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Some hypothetical class
class CFoo
{
public:
    CFoo();
    CFoo(const CFoo&);
    ~CFoo();

    CFoo& operator=(const CFoo&);

    static CFoo& GetInstance();

private:
    static CFoo mInstance;
};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static CFoo::mInstance;

CFoo::CFoo() {}

CFoo::CFoo(const CFoo&) {}

CFoo::~CFoo() {}

CFoo& CFoo::operator=(const CFoo&)
{
   return *this;
}

static CFoo& CFoo::GetInstance()
{
   return mInstance;
}
Topic archived. No new replies allowed.