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?
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...
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.
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