Reputation: 6149
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?
Upvotes: 2
Views: 327
Reputation: 5102
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...
Upvotes: 6
Reputation: 21
A static method can be called without creating an instance of the class.
class CMyClass
{
public:
static void Method1()
{
printf("Method1\n");
}
};
CMyClass::Method1(); // Prints "Method1".
Upvotes: 2
Reputation: 141
For that you should use the static
modifier. See documentation here: http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
Upvotes: 0
Reputation: 960
You can also create private constructor of such class with static methods to prevent from creating any instances
Upvotes: 0
Reputation: 1030
Yes, it is possible. If you want to use of class without having instance of it, you must use static functions.
Upvotes: 1
Reputation: 3471
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.
Upvotes: 2