Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A class which does not need an instance

Is it possible to make a class which does not need to be instantiated? In other words, is it possible to use functions of that class without having an instance of it?

like image 562
Shibli Avatar asked Feb 20 '26 14:02

Shibli


2 Answers

You can use static functions, those are bound to the Class, not an instance.

class Test{
    static void 
    doSomething()
    {
        std::cout << "something" << std::endl;
    }
}

int
main(int argc, char** argv)
{
    Test::doSomething(); //prints "something" without instance of Test
}

Otherwise you could build a Singleton, in which case the class itself would hold the instance, but I am not sure if this is what you wanted to know...

like image 87
Theolodis Avatar answered Feb 22 '26 06:02

Theolodis


You could make all member functions and variables static, but then one starts to wonder why it should be a class, and not a namespace.

There is a good reason, though: you may want to use a class template like this. C++14 will add variable templates, which make the same possible without a class. A class also allows access control; you can fake this for the non-template case with anonymous namespaces, but a class may be more natural.

like image 21
Anton Golov Avatar answered Feb 22 '26 05:02

Anton Golov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!