Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 805
ModdedLife Avatar asked Jan 14 '23 03:01

ModdedLife


1 Answers

You got it almost right.

Declaration:

static Singleton& instance();

Definition:

Singleton& Singleton::instance() {
  static Singleton myObj;
  return myObj;
}
like image 198
Angew is no longer proud of SO Avatar answered Jan 30 '23 23:01

Angew is no longer proud of SO