1

I have a class 'TcpCom' in which I would like a boost.asio tcp socket to be a class member so that all of the class functions won't have to take in a TCP socket as a parameter (breaking the generic design of the 'COM' base class i'm trying to make). However, I'm confused about how to properly initialize the socket in the member initialization list of the class.

Normally it would be created using:

boost::asio::io_service io_service;
boost::asio::ip::tcp::socket tcpSocket(io_service);

Previously when I ran into a similar issue I made the object class member a unique_ptr of the object that I initialized using new in the member initialization list, but later read that was bad practice. Is there a good way to make this design work, or should TcpCom just take in a TCP socket as a parameter?

#ifndef TCPCOM_H
#define TCPCOM_H
#include "COM.h"
#include <boost/asio.hpp>

class TcpCom : public COM {

public:
    TcpCom() : remoteHost(""), remotePort(""), connectedToRemoteHost(false)
    { }
    void sendMessage();
    void connectToRemoteHost(std::string host, std::string port);

private:
    //Needs to be initialized
    boost::asio::io_service io_srv;
    //Needs to be initialized
    boost::asio::ip::tcp::socket tcpSocket;

    std::string remoteHost;
    std::string remotePort;
    bool connectedToRemoteHost;
};

#endif

-

#ifndef COM_H
#define COM_H
#include <string>

class COM {
    public:
        COM();
        virtual void sendMessage() = 0;
        virtual void connectToRemoteHost(std::string host, std::string port) = 0;
        bool connectedToRemoteHost;
        virtual ~COM();
    protected:
    private:
};

#endif // COM_H
tyler124
  • 613
  • 1
  • 8
  • 20

2 Answers2

3

You'd do it pretty much as you do when they are automatic variables:

TcpCom() : io_srv(), tcpSocket(io_srv), remoteHost(""),
           remotePort(""), connectedToRemoteHost(false)
{}

There is one caveat however. The initialization order of the members is determined by their order in the class definition, and not the order written in the member initializer list. So keep that in mind if you move stuff around, because you'd run into undefined behavior if you aren't careful.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1

In cases like this, I would consider NSMI:

#include <boost/asio.hpp>

class TcpCom : public COM {

  public:
    void sendMessage();
    void connectToRemoteHost(std::string host, std::string port);

  private:
    boost::asio::io_service io_srv;
    boost::asio::ip::tcp::socket tcpSocket {io_srv};

    std::string remoteHost;
    std::string remotePort;
    bool connectedToRemoteHost = false;
};
sehe
  • 374,641
  • 47
  • 450
  • 633