c++ – Classes with self-creating static attributes and methods

Question:

Hi, today at the company I work for I saw a different way of creating an object, I asked why? And they replied that the company's standard is not to use static objects, I found it interesting. I tried to reproduce the code at home to test it, but I'm not getting it, I don't remember exactly how it was. Then two questions came to me: What is the usability of this besides a configuration class? What should I do to compile correctly? (Compilation errors followed by codes).

Error: Undefined reference to 'Base::_obj'

#include <iostream>

class Base{

public:
    static Base* _obj;

    Base()
    {
        std::cout << "Fui criado!\n";
    }

    void falar()
    {
        std::cout << "Alô\n";
    }

    static Base* getBase()
    {
        if(!_obj)
        {
            _obj = new Base();
        }

        return _obj;
    }

};

int main()
{
    Base::getBase()->falar();

    return 0;

}

–Edit–

I saw it in my work, and this one below is more or less how the code is, also seeing that link that the user commented below, but an error continues to appear in the compilation, I don't know if I need to pass a parameter when compiling. (error followed by code).

o.cpp:(.text$_ZN4Base7getBaseEv[__ZN4Base7getBaseEv]+0x2d)||undefined reference to 'Base::_obj'

//https://pt.wikipedia.org/wiki/Singleton
//-fpermissive flag activated
#include <iostream>


class Base{

private:
    static Base* _obj;

    Base()
    {
        std::cout << "Fui criado!\n";
    }

public:

    void falar()
    {
        std::cout << "Alô\n";
    }

    static Base* getBase()
    {
        if(!_obj)
            _obj = new Base;

        return _obj;
    }
};

Base* _obj = nullptr;

int main()
{

    Base* b = Base::getBase();

    return 0;

}

Answer:

I managed to solve it! I noticed that the edit I did, I didn't set the static pointer correctly to null, it follows the updated code, now compiling:

//https://pt.wikipedia.org/wiki/Singleton
//-fpermissive flag activated
//https://pt.stackoverflow.com/questions/482918
#include <iostream>

class Base{

private:
    //meu objeto único estático
    static Base* _obj;

    //construtor em private para que não seja possível acessar de fora da classe
    Base()
    {
        std::cout << "Fui criado!\n";
    }

public:

    //teste
    void falar()
    {
        std::cout << "Alo\n";
    }

    //getHandle retorna o _obj se estiver instanciado
    //se não, inicia o objeto
    static Base* getBase()
    {
        if(!_obj)
            _obj = new Base;

        return _obj;
    }
};

//inicializa como nullptr
Base* Base::_obj = nullptr;

int main()
{
    //mãos a obra!
    Base::getBase()->falar();

    return 0;

}


Scroll to Top