2

I have this c# code:

class Animacion
{

    private static Animacion instancia;
    public static Animacion Instance
    {
        get
        {
            if (instancia == null)
            {
                instancia = new Animacion();
            }
            return instancia;
        }
    }

I want to convert that code to c++, I tryed to use a code converter from tangible software solutions and I got this:

//.h file code:

class Animacion
{

    private:
        static Animacion *instancia;
    public:
        static Animacion *getInstance() const;
};

//.cpp file code:

Animacion *Animacion::getInstance() const
{
    if (instancia == nullptr)
    {
        instancia = new Animacion();
    }
    return instancia;
}

When I use the code generated from the converter I get errors like:

error: C2272: 'getInstance' : modifiers not allowed on static member functions

can anyone help me?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Rud Banisterloid
  • 315
  • 1
  • 2
  • 6
  • 1
    https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289 – Galik Sep 13 '15 at 20:03

1 Answers1

2

static Animacion *getInstance() const; get rid of the const. There's no point making a static class member function const in c++, hence the compiler error.


Also the established idiom for singletons in c++ looks rather like:

class Animacion {

private:
    Animacion() {}
    Animacion(const Animacion&) = delete;
    Animacion& operator=(const Animacion&) = delete;
public:
    static Animacion& getInstance() {
        static Animacion theInstance;
        return theInstance;
    }
};

Further you should note, that Singleton is a really questionable design pattern, and you likely could live without it, in preference of an injected interface for the clients. That would help in decoupling implementation, from usage.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190