class that only instantiate ones

Nov 15, 2015 at 6:37am
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
Nov 15, 2015 at 7:51am
Google "Singleton"

Nov 15, 2015 at 10:16am
Google "Singleton"

i dont think you understand my question. i know about singleton pattern

my question is, does it really make sense to write a class if i will only instantiate it ones?
Nov 15, 2015 at 10:20am
Did you mean instantiate it 'once' ?
Nov 15, 2015 at 10:37am
closed account (48T7M4Gy)
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.

http://programmers.stackexchange.com/questions/213343/is-it-a-bad-idea-to-create-a-class-which-will-only-have-one-instance
Last edited on Nov 15, 2015 at 11:31am
Nov 15, 2015 at 11:23am
> 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.
Topic archived. No new replies allowed.