Initialiser class must have parameter?


#1

Hi. New user here with a problem I could not find an answer anywhere …
I made a class ‘Sensor’ and put it in the map ‘lib/Sensor/src’:
The minimun content is

Sensor.h:

#ifndef sensor_h
#define sensor_h

#include <Arduino.h>

class Sensor
{
private:

public:
Sensor();

float getTemperature(void);
};

#endif

Sensor.cpp:

#include <Arduino.h>
#include “Sensor.h”

Sensor::Sensor()
{
};

float Sensor::getTemperature(void)
{ // eerste nibble is decimaal
return 54.32;
};

main.cpp:

#include <Arduino.h>
#include “Sensor.h”

Sensor sens();

void setup() {
sens.getTemperature();
};

void loop() {
};

This gives me an error message
src\main.cpp: In function ‘void setup()’:
src\main.cpp:8:10: error: request for member ‘getTemperature’ in ‘sens’, which is of non-class type 'Sensor()'
sens.getTemperature();
This error message does not appear when I add a parameter to the constructor (which I don’t use in my code):

Sensor.h:

#ifndef sensor_h
#define sensor_h

#include <Arduino.h>

class Sensor
{
private:

public:
Sensor(int);

float getTemperature(void);
};

#endif

Sensor.cpp:

#include <Arduino.h>
#include “Sensor.h”

Sensor::Sensor(int no_use)
{
};

float Sensor::getTemperature(void)
{ // eerste nibble is decimaal
return 54.32;
};

main.cpp:

#include <Arduino.h>
#include “Sensor.h”

Sensor sens(1);

void setup() {
sens.getTemperature();
};

void loop() {
};

Is there an explanation or better: how can I build my class without this extra parameter?
Thanks for your reactions.


#2

When you have your class declared without a constructor you create the object like Sensor sens;, not Sensor sens();.

As soon as you add a constructor with an int parameter your syntax of Sensor sens(1) is correct.

Also this question is about C/C++ and not PIO itself. You should use the Arduino Stackexchange (Stackoverflow) site or the Arduino Forum for this.