Compiler errors when playing with members versus references. [Boost asio]

Nov 2, 2016 at 10:00pm
Consider this code which works perfectly. It opens a socket and sends a message to an IP and port:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <boost/asio.hpp>

struct Client
{
   boost::asio::io_service& io_service;
   boost::asio::ip::tcp::socket socket;

   Client(boost::asio::io_service& svc) 
       : io_service(svc), socket(io_service) 
   {
       boost::asio::ip::tcp::resolver resolver(io_service);
       boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query("127.0.0.1", "32323"));
       boost::asio::connect(this->socket, endpoint);
   }

   void send(std::string const& message) {
       socket.send(boost::asio::buffer(message));
   }
};

int main() 
{
   boost::asio::io_service svc;
   Client client(svc);

   client.send("hello world\n");
   client.send("bye world\n");
}


Next, consider this code. It does the same thing, except the io_service class is now a member of Client as opposed to a reference to some super-instance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <boost/asio.hpp>

struct Client
{
   boost::asio::io_service io_service;
   boost::asio::ip::tcp::socket socket;

   Client() 
       : io_service(), socket(io_service) 
   {
       boost::asio::ip::tcp::resolver resolver(io_service);
       boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query("127.0.0.1", "32323"));
       boost::asio::connect(this->socket, endpoint);
   }

   void send(std::string const& message) {
       socket.send(boost::asio::buffer(message));
   }
};

int main() 
{
   Client client();

   client.send("hello world\n");
   client.send("bye world\n");
}


I can't explain it, but when I try to compile the latter I get:
[stew@Romulus test]$ make client
g++ -o client client.cpp -L/usr/lib -lboost_system -lpthread
client.cpp: In function ‘int main()’:
client.cpp:25:11: error: request for member ‘send’ in ‘client’, which is of non-class type ‘Client()’
    client.send("hello world\n");
           ^~~~
client.cpp:26:11: error: request for member ‘send’ in ‘client’, which is of non-class type ‘Client()’
    client.send("bye world\n");
           ^~~~
make: *** [makefile:8: client] Error 1


Can someone help me to understand the error? Why is the send method suddenly treated as if it wasn't a member? If I make Client a class and put everything in public: I get the same thing.
Last edited on Nov 2, 2016 at 10:09pm
Nov 3, 2016 at 7:32am
Because on line 23 you have the prototype of the function client which returns an object of type Client.

So either you omit the () or you change them to {}.
Nov 3, 2016 at 8:12am
Wow, it's the simple mistakes that really get you!

Thanks.
Topic archived. No new replies allowed.