bertmoog
bertmoog

Reputation: 483

How to access a singleton from other classes C++

I can't find any answer to this question for C++ (for other languages yes) though I've searched for a number of hours. How can I access a Singleton from another class?

Declaration:

#include "Store.h"
Store *store = Store::Instance();      // Singleton

int main()
{
  store->GetDepts();
  return 0;
}

I want to be able to access it from my Customer Proxy class:

#include "Store.h"
class Cust_Proxy
{
public:
  Cust_Proxy(string cust_name)
  {
    name_ = cust_name;
  }
  void AddItem(Item item)
  {
    store->AddItemToShoppingCart(item);    // or something, just for example
  }
private:
  string name_;
  ShopCart cart_;
};

I've tried passing it as a parameter but obviously there's no public constructor in the singleton "store":

void AddItem(Store *store) 
{ 
  store = Store::Instance();
  // Do Stuff; 
}

Any help would be greatly appreciated. Thank you.

Upvotes: 1

Views: 2583

Answers (1)

R Sahu
R Sahu

Reputation: 206737

Instead of

store->AddItemToShoppingCart(item);

use

Store::instance()->AddItemToShoppingCart(item);

You don't need to store the pointer to the singleton in main.cpp or any other function that uses the singleton. Access the singleton by calling Store::instance() whenever you need it.

In main, you can use:

int main()
{
  Store::instance()->GetDepts();
  return 0;
}

and remove the line

Store *store = Store::Instance();      // Singleton

Upvotes: 4

Related Questions