I am trying to create a simple class, and I can't seem to get this code to compile. The code and the error message are below.
#ifndef bcd_input
#define bcd_input
#include <arduino.h>
class bcd_input
{
private:
int bit_1;
int bit_2;
int bit_3;
int bit_4;
public:
bcd_input();
int IntegerValue();
};
#endif
bcd_input::bcd_input();
int bcd_input::IntegerValue()
{
int returnVal = (bit_4 << 3 | bit_3 << 2| bit_2 << 1 | bit_1);
return returnVal;
};
Error Message:
bcd_input.cpp:17:15: error: expected unqualified-id before ')' token
bcd_input();
^
bcd_input.cpp:9:1: error: an anonymous struct cannot have function members
{
^
bcd_input.cpp:19:1: error: abstract declarator '' used as declaration
};
It is a good practice to use capital letters on include guards, so you avoid name conflicts with classes or variables. Also, you are declaring the constructor outside the class, but you should actually implement it. If you want an empty constructor, you can add brackets after the parenthesis.
#ifndef BCD_INPUT
#define BCD_INPUT
#include <Arduino.h>
class bcd_input
{
private:
int bit_1;
int bit_2;
int bit_3;
int bit_4;
public:
bcd_input();
int IntegerValue();
};
#endif
bcd_input::bcd_input() {};
int bcd_input::IntegerValue()
{
int returnVal = (bit_4 << 3 | bit_3 << 2| bit_2 << 1 | bit_1);
return returnVal;
};
This compiles on my environment. Anyway, I would separate the class declaration from the implementation, this is, having a .h and a .cpp file.
A Constructor Function is a member function under public: specifier (with its arguments) and is intended to initialize the member variables under private: specifier. It always comes with the same name of the class name. By virtue of C++’s mechanism, it is automatically called upon when a new object is created. The constructor functiondoes not have any return data type even no void either. For example (to blink L of UNO):