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;
}
Does the code you saw resemble this pattern? https://pt.wikipedia.org/wiki/Singleton#Em_c++
– aviana
That, more or less, I wrote him down today.
– Morvy