Dark Sorrow
Dark Sorrow

Reputation: 1897

Pass data from one class to another without passing object

I am using paho-mqtt c++ library. I'm using the asynchronous communication model. I have created Callaback class and implemented necessary methods. I have also created a mqtt_client class which holds transmit and recieve queues along with several methods like connect, send_data, get_recieved_data, etc.

class mqtt_client
{
private:
    std::queue<std::string>     receive_queue, transmit_queue;
public:
    bool connect(void){
        mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
        callback cb(client, connOpts);
        client.set_callback(cb);
    }
    bool send_data(const std::string& data){
        transmit_queue.push(data);
        //if not tranmitting then start transmitting
    }
    std::string get_recieved_data(void);
};

class callback : public virtual mqtt::callback
{
public:
    void connected(const std::string& cause) override;
    void connection_lost(const std::string& cause) override;
    void delivery_complete(mqtt::delivery_token_ptr tok) override; //Pop data from mqtt_client::transmit_queue (if available)
    void message_arrived(mqtt::const_message_ptr msg) override; //Push data to mqtt_client::receive_queue
};

In callback::message_arrived method's implementation. I wish to copy the payload of the message and push it to mqtt_client::receive_queue which is located in mqtt_client.

Similarly callback::delivery_complete checks if data is available in mqtt_client::transmit_queue and if more data is present it will transmit the next message.

I wish to know what are my option over here. I don't wish to send mqtt_client object to class callback.

In Andorid I had used intent or interface to achive this.

Upvotes: 2

Views: 440

Answers (1)

James Picone
James Picone

Reputation: 1600

As discussed in the comments, you probably do want to pass a reference to mqtt_client to your callback object. This is straightforward to do:

class mqtt_client
{
public:
    bool connect(){
        mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
        callback cb(*this, client, connOpts);
        client.set_callback(cb);
    }
};

class callback : public mqtt::callback
{
private:
    mqtt_client& client;
public:
    callback(mqtt_client& _client, mqtt::async_client async_client, some_type connOpts) :client(_client) {}
};

One strange aspect of your code is that you're creating an mqtt::async_client on the stack of your connect() function, passing it to a callback object you're also creating on the stack, and then passing the callback object to the async client. Those objects will all get destroyed when that function finishes; it's very unlikely that they're meant to be used like that. I'm not familiar with the MQTT library and so can't tell you how they're meant to be used.

Upvotes: 2

Related Questions