Maik
Maik

Reputation: 111

using singleton class to be reached from all classes

I have a weird question. It is so weird it is probably quite easy to solve.

I created a software and I need to implement a class Sing with an sing objeect that must be reached from all classes from the software. Therefore I created it as singleton object in the main function.

My problem is, how can the object sing be reached from other classes (like ClassA) without creating pointers which are handovered by a pointer to every single class in the code.

All the class definition is located in the sing.h file. If I put the definition into the sing.cpp file the compiler will fail.

I managed to create this sing object, but it is not visible from ClassA. How can the object sing be seen without handing over pointers to the constructors of each class?

sing.h file:

#ifndef _SING_H_
#define _SING_H_

//declaration
class Singleton
{
public:
    static Singleton* Instance();
    static Singleton* InstanceSlave();
    int a;
    int setTest(int);

protected:
    Singleton(){}

private:
    static Singleton* _instance;    
    static Singleton* _instanceSlave;

};

//definitions (only work in header file, not in .cpp file

Singleton* Singleton::_instance =0;

Singleton* Singleton::Instance()
{

    if (_instance == 0 )
    {
        _instance = new Singleton;
    }
    return _instance;

}

int Singleton::setTest(int b)
{
 return 1;
}

#endif _CONF_H_

main.cpp file:

int main()
{
 Singleton* sing = sing->Instance();
 sing->setTest(2);

 ClassA* classa = new ClassA();
}

main.h file:

#inlucde <iostream>
#include "sing.h"
#include "classA.h"

inside the ClassA I would like to have something like this:

classA.h

#inlude sing.h
class classA
{
 public:
  void doSomeThing(int);
}

classA.cpp:

#include ClassA.h
{
 void ClassA::doSomeThing(int a)
 {
  sing.setTest(a);
 }
}

Upvotes: 0

Views: 74

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

My problem is, how can the object sing be reached from other classes (like ClassA) without creating pointers which are handovered by a pointer to every single class in the code.

The canonical way is to use Scott Meyer's Singleton and provide a static function like

    static Singleton& Instance() {
         static Singleton theInstance;
         return theInstance;
    }

Usage is

Singleton::Instance().setTest(2);

In general the Singleton Pattern isn't really considered a good technique, because the coupling with the rest of the code is too tight. It's better to use interfaces (abstract classes) and pass these around as necessary.

Upvotes: 3

Joseph Willcoxson
Joseph Willcoxson

Reputation: 6050

Just use

Singleton::Instance()->setTest(a);

Upvotes: -1

Related Questions