0

I have problem with C++ class. Is there have any way to reuse variable in the same class in the header file?

I have try

PubSubClient mqttClient(this->secureClient);
PubSubClient mqttClient(mqtt.secureClient);

but fail. Why?

#ifndef __MQTT_H_
#define __MQTT_H_

#include "Arduino.h"
#include "WiFi.h"
#include "WiFiClientSecure.h"
#include "PubSubClient.h"

class MQTT
{
public:

bool initWiFi();
String macAddress6btye(void);
void callback(char *topic, byte *payload, unsigned int length);
bool mqttConnect();
bool mqttPublish(const String &endPoint, const String &payload);
int getStrength(uint8_t points);

private:
    WiFiClientSecure secureClient;
    PubSubClient mqttClient(this->secureClient);
};

#endif
273K
  • 29,503
  • 10
  • 41
  • 64
Samuel
  • 228
  • 2
  • 13
  • 2
    I think you might need to invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Jul 29 '22 at 06:10
  • CPP is C preprocessor. It does not have classes. What you have mentioned is C++. – 273K Jul 29 '22 at 06:10
  • On another (but unrelated) note, your function named `callback` worries me. Callback functions need special handling if done as non-static member functions. You might want to study more about pointers to member functions and the difference between pointers to non-member functions. – Some programmer dude Jul 29 '22 at 06:17
  • `__MQTT_H_` is a reserved name. You shouldn't be using it in your own code. All identifiers that contain two consecutive underscores (`__`) or start with underscore followed by a capital letter are reserved for the implementation. – Jesper Juhl Jul 29 '22 at 07:00

1 Answers1

3

The declaration

PubSubClient mqttClient(this->secureClient);

is treated as a function declaration. An invalid one.

If you want to initialize the member variable (using other member variables), you need to do it with a constructor initializer list:

class MQTT
{
public:
    MQTT()
        : secureClient(),
          mqttClient(secureClient)  // Initialization here
    {
        // Empty function body
    }

    // ...

    WiFiClientSecure secureClient;
    PubSubClient mqttClient;  // No initialization here
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I found a solution should be working ```MQTT(WiFiClientSecure secureClient) { PubSubClient mqttClient(secureClient); }; ``` The relation between the variable, constructor and the class is quite a complicated one. Still not very understand it. @Some Programmer dude, Thank for the tips. It open a new area for me. – Samuel Jul 29 '22 at 18:12
  • @Samuel That code you show defines a *local* variable with the name `mqttClient` inside the constructor body. It's a totally separate variable from the member variable of the same name. Why don't you just copy-paste the code I've shown in my answer (now updated to initialize both member variables)? – Some programmer dude Jul 30 '22 at 09:06