In this code we have static class variable and i need someone to explain what happens here and how i can use it.It is a static class variable and a function that gets the variable with a reference.
class Constructor
{
private:
static Constructor constructor;
public:
static Constructor* constructor();
};
Constructor Constructor::constructor;
Constructor* constructor::constructor()
{
return &constructor;
}
Once you remove the errors so that it compiles
class Constructor
{
private:
static Constructor constructor_;
public:
static Constructor* constructor();
};
Constructor Constructor::constructor_;
Constructor* Constructor::constructor()
{
return &constructor_;
}
you end up with a single private instance of Constructor in the static variable Constructor::constructor_ that can only be accessed through its static public Constructor::constructor() method. This type of construction which allows only the creation of a single instance of a class is called a singleton. It is used like this:
int main(){
auto* s1 = Constructor::constructor();
auto* s2 = Constructor::constructor();
std::cout << (s1 == s2);
}
See working version here.
See Thread-Safe Initialization of a Singleton for additional information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With