How do I create a static method that returns a reference to an object of that class?

c++, declaration, object, reference, static-methods

Solution

You got it almost right.

Declaration:

static Singleton& instance();

Definition:

Singleton& Singleton::instance() {
  static Singleton myObj;
  return myObj;
}

Problem

Im working on a programming assignment involving the use of static variables/methods. This is one of the requirements, and I'm not exactly sure the proper syntax for declaring it in the header and defining it in the class file: "Declare a static method of the class with a return type of a reference to an object of the class; name this method “instance”." heres my guess for declaring: ``` static &Singleton instance(); ``` heres my guess for defining: ``` static &Singleton::Singleton instance(){ static myObj; return myObj; } ``` I don't think thats correct.. Could anyone confirm/correct me? Thanks!

Original source