Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to defer member initialization to the constructor body?
    text
    copied!<p>I have a class with an object as a member which doesn't have a default constructor. I'd like to initialize this member in the constructor, but it seems that in C++ I can't do that. Here is the class:</p> <pre><code>#include &lt;boost/asio.hpp&gt; #include &lt;boost/array.hpp&gt; using boost::asio::ip::udp; template&lt;class T&gt; class udp_sock { public: udp_sock(std::string host, unsigned short port); private: boost::asio::io_service _io_service; udp::socket _sock; boost::array&lt;T,256&gt; _buf; }; template&lt;class T&gt; udp_sock&lt;T&gt;::udp_sock(std::string host = "localhost", unsigned short port = 50000) { udp::resolver res(_io_service); udp::resolver::query query(udp::v4(), host, "spec"); udp::endpoint ep = *res.resolve(query); ep.port(port); _sock(_io_service, ep); } </code></pre> <p>The compiler tells me basically that it can't find a default constructor for udp::socket and by my research I understood that C++ implicitly initializes every member before calling the constructor. Is there any way to do it the way I wanted to do it, or is it too "Java-oriented" and not feasible in C++?</p> <p>I worked around the problem by defining my constructor like this:</p> <pre><code>template&lt;class T&gt; udp_sock&lt;T&gt;::udp_sock(std::string host = "localhost", unsigned short port = 50000) : _sock(_io_service) { udp::resolver res(_io_service); udp::resolver::query query(udp::v4(), host, "spec"); udp::endpoint ep = *res.resolve(query); ep.port(port); _sock.bind(ep); } </code></pre> <p>So my question is more out of curiosity and to better understand OOP in C++</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload