Basic C++ problem - Using variable within the class [duplicate] - c++

This question already has answers here:
Call constructor inside a call to another constructor
(2 answers)
Most vexing parse C++11
(2 answers)
Closed 7 months ago.
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

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
};

Related

What effect does `static` have on a method in a namespace? [duplicate]

This question already has answers here:
Error in calling a static function in a namespace
(2 answers)
Static function vs Static member functions C++
(1 answer)
The static keyword and its various uses in C++
(9 answers)
Closed 6 months ago.
Does static mean anything on func2 in the context of a namespace? Both methods appear to be equivalent.
// MyHeader.h
namespace TestNameSpace
{
int func1() { return 1; }
static int func2() { return 2; }
}
// SomeFile.cpp
#include "MyHeader.h"
// ...
int test1 = TestNameSpace::func1(); // 1
int test2 = TestNameSpace::func2(); // 2
static functions (which are not member of classes) are only visible in the compilation unit they are defined in. Apart from that there should not be any difference between those two

Compiler send me errors when I use vector <XClass> Yname(number_of_elements); inside of another class [duplicate]

This question already has answers here:
Why can't member initializers use parentheses?
(2 answers)
Initialization of member variable via parentheses doesn't work [duplicate]
(1 answer)
can not define and init a class member by Parentheses [duplicate]
(1 answer)
Closed 9 months ago.
SOLVED. Thaks to you all!!! :)
Im trying to create a vector that contains objects of another class but the compiler send me some errors.
this is the first class
ClassB.h
#pragma once
#include <string>
class B {
public:
B();
std::string Avariable = "Hi from Class´ B member";
};
this is the socond one
ClassA.h
#pragma once
#include "ClassB.h"
#include <vector>
class A {
public:
A();
std::vector <B> VectorOfB (10);
//The c++´s book says the 10 mean 10 elements in the vector
};
main.cpp
#include <iostream>
#include "ClassA.h"
int main() {
A *MyA;
MyA = new A;
//attempt to access the phrase "Hi from class´B element"
std::cout << MyA->VectorOfB[0];
}
In this link you can find it Deitel C.7 look for page 97 lines 13 and 14.
Unfortunately, the compiler sees the offending line as a member declaration of the 'Game' class:
vector <NormalCoin> NormalCoins(10); // <- notice: it looks like a function!
The solution is to instead use an assignment:
vector<NormalCoin> NormalCoins = vector<NormalCoin>(10);
You may also use a brace-enclosed initializer, but as noted in the comments this may be less safe:
vector <NormalCoin> NormalCoins{10};
( see: When to use the brace-enclosed initializer? for reasons to use )
EDIT: added suggestion to initialize vector by assignment instead, and removed mention of Most Vexing Parse (thanks to user17732522
)

Qt Optional Argument has no matching function call [duplicate]

This question already has answers here:
Default value of function parameter
(5 answers)
Closed 3 years ago.
I'm getting a compile error when trying to use a method defined as having and option argument. The error message is this:
error: no matching function for call to 'ConsoleWidget::logInfo(const
char [32])'consoleWidget->logInfo("This is logging an info message");
Below are my files.
(header) .h
#ifndef CONSOLEWIDGET_H
#define CONSOLEWIDGET_H
#include <QTextEdit>
#include <QAction>
#include <QColor>
class ConsoleWidget : public QTextEdit
{
Q_OBJECT
public:
explicit ConsoleWidget(QWidget *parent = nullptr);
public slots:
void logInfo(const QString& text, const bool includeTimestamp /*=false*/);
};
#endif // CONSOLEWIDGET_H
cpp (.cpp)
void ConsoleWidget::logInfo(const QString &text, bool includeTimestamp = false)
{
...
}
(main) .cpp
auto *consoleWidget = new ConsoleWidget(this);
consoleWidget->logInfo("This is logging a message!");
A default argument is (secretly) evaluated and passed by the caller of the function, so it must be known where the function is called.
If the compiler has seen
void foo(int x = 37);
and then encounters
foo();
it will replace that with the equivalent of
foo(37);
If it has seen only void foo(int x);, there will not be a function with a matching prototype, because the function always takes an int parameter.
(This is different from, for instance, Python, where default arguments are evaluated when the function is defined and the calling code doesn't need to care.)
The solution is to move your default value from the function definition to its declaration.

Using the const keyword in header and class files functions C++ [duplicate]

This question already has answers here:
When to use const and const reference in function args?
(4 answers)
C++ Const Usage Explanation
(12 answers)
Closed 4 years ago.
I am trying to learn how to use the keyword const while making header and class files (using OOP). Aka learning the correct way to incorporate the keyword 'const' while making and calling the functions.
// Example.h
class Example {
public:
string getName() const;
void setName(const string aName);
private:
const string name;
};
// Example.cpp
#include "Example.h"
#include <string>;
#include <iostream>;
Example::Example();
string Example::getName() const{
return name;
// the following setter does not work
void Example::setName(const string aName){
name = aName;
}
I figured out how to declare variable and getter/setter functions, using const in the header file. Just need help in using const with setter function in class file.
// the following setter does not work
void Example::setName(const string aName){
name = aName;"
Of course it doesn't. You declared name to be const so you cannot assign to it (you can only initialize it). Remove const from name and your setter will work.

C++ callback to class function

I'm using the Arduino IDE and the things network arduino library to create a LoRa mote.
I have created a class which should handle all the LoRa related functions. In this class I need to handle a callback if i receive a downlink message.
The ttn library has the onMessage function which I want to setup in my init function and parse another function, which are a class member, called message.
I'm getting the error "invalid use of non-static member function".
// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>
TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);
LoRa::LoRa(){
}
void LoRa::init(){
// Set the callback
ttn.onMessage(this->message);
}
// Other functions
void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
// Stuff to do when reciving a downlink
}
and the header file
// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h
#include "Arduino.h"
#include <TheThingsNetwork.h>
// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial
// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868
class LoRa{
// const vars
public:
LoRa();
void init();
// other functions
void message(const uint8_t *payload, size_t size, port_t port);
private:
// Private functions
};
#endif
I have tried:
ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);
However none of them worked as I had expected.
You're trying to call a member function (that means, a function belonging to a member of a class type) without using a class member. That means, what you'd usually do is instantiate a member of your class LoRa first, then call it like:
LoRa loraMember;
loraMember.message();
Since you're trying to call that function from inside the class itself, without a member of the class calling the init(), you have to make the function static like:
static void message(const uint8_t *payload, size_t size, port_t port);
Then you can use LoRa::message() from anywhere as long as it's public, but calling it just like that will give you another compiler error, since the interface of message asks for "const uint8_t *payload, size_t size, port_t port". So what you'd have to do is call message like:
LoRa::message(payloadPointer, sizeVar, portVar);`
When you call ttn.onMessage(functionCall) what happens is that the function call gets evaluated, then what is returned by that function gets put into the parentheses and ttn.onMessage is called with that. Since your LoRa::message function returns nothing (void) you'll get another error here.
I suggest a good book on C++ basics to get you started - book list
Good luck!
I Solved the problem by making the message function a normal function outside the class. Not sure if it is good practice - but it works.
// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>
TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);
void message(const uint8_t *payload, size_t size, port_t port)
{
// Stuff to do when reciving a downlink
}
LoRa::LoRa(){
}
void LoRa::init(){
// Set the callback
ttn.onMessage(message);
}
You should pass arguments to massage as indicated by its prototype:
void message(const uint8_t *payload, size_t size, port_t port);
Since massage returns void, it should not be used as an argument to other functions.