so i have a class called Server, i dont need to instantiate it more than one.
i only need one Server server thats it
should i consider making a class of it? or should i just write a functions and global variables in header file? im confused
Classes have the advantage of formalising data abstraction, encapsulation and hiding and project management and control so why not use it for a single server object when any cost or overhead is minimal and the alternatives are slightly less (at least) functional and that is without cosiderering interact with other possible classes and aspects such as inheritance.
> does it really make sense to write a class if i will only instantiate it ones?
Usually no; in many cases singleton is an anti-pattern. Use a namespace instead.
Header (.h):
1 2 3 4
namespace server
{
// declarations of server functions
};
Implementation (.cpp):
1 2 3 4 5 6 7 8 9 10 11 12 13
#include "server.h"
namespace // internal linkage, not visible outside
{
// server data
// server helper functions
// other server implementation details
}
namespace server
{
// definitions of server functions
}
A singleton object should be used if and only if an object is actually required.
For instance, alternate implementations accessed via a pure polymorphic interface needs to be supported;
overloaded operators would be desirable etc.