Marek Chuchro
Marek Chuchro

Reputation: 11

Cannot access member from another function c++ class

So basically my code looks like this:

void SimpleMQTT::begin() {
    Serial.println("setserver");
    WiFiClient espClient;
    PubSubClient client(espClient);
    client.setServer(this->serverAddress, this->port);
    while(!client.connected()) {
        if (client.connect(this->deviceName)) {
            Serial.println("connected to mqtt");
            client.publish("connecting", "connected");
        } else {
            Serial.println("failed to connect");
        }
    }
    this->client = & client;
    //WORKING
    this->client->publish("connecting","conn2");
}

void SimpleMQTT::broadcast(char* channelName, char* message) {
    Serial.println("broadcasting");
    Serial.println(this->deviceName);
    //NOT WORKING
    this->client->connected();
    Serial.println("after broadcast");
}

accessing a member from the function begin() works, but accessing the same member from the function broadcast() doesn't work. Arduino is sending an exception to Serial (see screenshot).

Error screenshot

Upvotes: 1

Views: 128

Answers (1)

Liran Funaro
Liran Funaro

Reputation: 2878

You seem to have a dangling pointer issue. You create the client object on the stack:

PubSubClient client(espClient);

then refer to it:

this->client = & client;

However, once the function SimpleMQTT::begin() exits, client is deleted along with the rest of the function's stack.

You should create the client object on the heap instead. Change the code to:

void SimpleMQTT::begin() {
    Serial.println("setserver");
    WiFiClient* espClient = new WiFiClient();
    PubSubClient* client = new PubSubClient(espClient); // Allocate an object on the heap
    client.setServer(this->serverAddress, this->port);
    while(!client->connected()) {
        if (client->connect(this->deviceName)) {
            Serial.println("connected to mqtt");
            client->publish("connecting", "connected");
        } else {
            Serial.println("failed to connect");
        }
    }
    this->client = client;
    this->client->publish("connecting","conn2");
}

espClient should also be a member of your class.

Here is a more elaborate explanation of danling pointers.

Upvotes: 3

Related Questions