On Aug 5, 7:34*am, Ian Collins <ian-n...@hotmail.com> wrote:
> Paul Stam wrote:
>
> > Hi
>
> > I have probably a quite simple problem but I did not find a proper
> > design decision yet. Basically, I have 4 different inherited classes and
> > each of those classes has more than 10 methods.
>
> > Each of those classes should make use of the same TCP Socket; this
> > object keeps a socket open to the server throughout program execution.
> > My idea was to have the TCP obejct declared as "global" so that all
> > other classes can use it:
>
> > classTCP TCPSocket;
>
> > class classA
> > {
> > * * private:
> > * * public:
> > * * classA();
> > * * virtual void method1();
> > * * ...
> > };
>
> > class classB
> > {
> > * * private:
> > * * public:
> > * * classB();
> > * * virtual void method1();
> > * * ...
> > };
>
> > and so on for classC and classD...
>
> > Unfortunately, when declaring it like this my C++ compiler gives me an
> > error message that some initialized data is written in the executable
> > (???). So I am wondering if there is any other way I could declare this
> > TCP object so that it is available for ALL the other classes and its
> > methods? classA() is the first method that will be called when
> > initialising this subsystem.
>
> Have you considered making the TCPSocket instance a singleton? *This
> appears to be the pattern you are looking for.
>
> --
> Ian Collins
Hi Paul,
As Ian said, using the singleton approach for the TCPSocket would be a
good way of using it. However, you may eventually want to have more
than one TCPSocket. For that case, I would think passing TCPSocket
instance pointer to the classes when the instances of the classes are
created (possibly by using constructor). In that way, you can share a
instance between different classes.
Cheers,
Alex Kim
|