Boost logo

Boost Users :

Subject: Re: [Boost-users] class initialization problem
From: Igor R (boost.lists_at_[hidden])
Date: 2011-10-01 12:28:31


> I have a Server class inherited from a Listener class, with the latter being
> bases on the boost::asio example code.
>
> My problem is that the Listener class requires am boost::asio::io_service & in
> order to initialize its member variables.
>
> I wanted the Server class to be responsible for starting a thread, owning the
> io_service, and running it.
>
> It seems I cannot do that!
>
> class Server : public Listener
> {
> public:
>   Server()
>      :
>      Listener(ioService_)
>   {
>   }
>
>   // Snip
>
> protected:
>
>   boost::asio::io_service ioService_;
> };
>
>
> class Listener
> {
> public:
>
>   Listener(boost::asio::io_service & ioService)
>      :
>      socket_(ioService)
>   {
>   }
>
>   // Snip
>
> protected:
>   boot::asio::ip::tcp::socket socket_;
> };
>
> The above throws an unhandled exception in the initialization of the derived
> class.
>
> I suppose this is because ioService_ is not constructed yet? Since the C++
> rules, if I remember correctly, say the base class gets constructed before the
> members of the derived?
>
>
> So, I tried:
>
> Server()
>      :
>      ioService_(),
>      Listener(ioService_)
>   {
>   }
>
> to try and force it, but it still throws an exception.

Initialization order does not depend on the order of objects in the
initialization list, so you can't "force" anything this way.
But you can move io_service definition to Listener, and then access it
from Server.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net