Classes with Static attributes and methods that create themselves

Asked

Viewed 31 times

3

Hello, today at the company I work saw a different way to create an object, I asked why? And I was told 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 can’t remember how it was. Then came two questions: 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 in my work, and this below is more or less like the code, also seeing that link that the user Aviana commented below, but still appears an error in the compilation, I do not 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;

}

  • 3

    Does the code you saw resemble this pattern? https://pt.wikipedia.org/wiki/Singleton#Em_c++

  • That, more or less, I wrote him down today.

1 answer

1


I got it solved! I noticed that the edition I made, I did not correctly set the static pointer in null, follows the updated code, now compiling:

//https://pt.wikipedia.org/wiki/Singleton
//-fpermissive flag activated
///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;

}


Browser other questions tagged

You are not signed in. Login or sign up in order to post.