1

What I want to use has no default constructor - so in my class definition, I need to call a parameterized constructor inside that class.

My question is - how?

class ServerSocket
{
public:
    ....

private:
    ....
    asio::io_context io_context;
    tcp::socket socket(io_context); //the compiler will think this is a function definition - 
                    //but it isn't, I want to instantiate an object of type tcp::socket
                    //with io_context as a parameter

    ServerSocket()
    {
        //I thought about moving tcp::socket here, but then I won't have access to the socket accross the class
    }
};
Octavian Niculescu
  • 1,177
  • 1
  • 3
  • 24
  • 3
    `tcp::socket socket{io_context}`? Related: [Why is list initialization (using curly braces) better than the alternatives?](https://stackoverflow.com/q/18222926/11082165) – Brian61354270 Dec 15 '21 at 21:35
  • Is it your intention to make `ServerSocket`'s constructor `private`? – Drew Dormann Dec 15 '21 at 21:36
  • @DrewDormann yes, in this case my ServerSocket is a singleton :) but I didn't go into details because it is not related to my question – Octavian Niculescu Dec 15 '21 at 21:36
  • You don't need to have both the **declaration** of the `socket` class member and the **assignment** in the same place. `tcp::socket* socket;` can be declared in the class and allows you to construct the instance later. – Romen Dec 15 '21 at 21:37
  • @Brian yes - it worked - I didn't know about that. – Octavian Niculescu Dec 15 '21 at 21:37
  • @Brian add that as an answer, I'll accept it asap :)_ – Octavian Niculescu Dec 15 '21 at 21:38
  • @Romen tcp::socket has no default constructor, so I can't declare it – Octavian Niculescu Dec 15 '21 at 21:38
  • Might be good to add [Why C++11 in-class initializer cannot use parentheses?](https://stackoverflow.com/q/24836526/11082165) to the duplicate list as well. – Brian61354270 Dec 15 '21 at 21:40
  • I want to question the single-ness of server socket.. perhaps it's just interface to actual service, but then "socket" in name is a misnomer.. even is server operates with single socket at time, it have to be able to recreate it for normal operation, system configuration changes, error handling, etc. Socket is a file, a singleton controlling a file is..questionable. Typical singleton can't do that, they have a single life <. – Swift - Friday Pie Dec 15 '21 at 21:45

0 Answers0