One other option for an OOP solution even when there will only be one object instantiated is to force that object to be a Singleton. This gives you the nice encapsulation and abstraction of a class and ensures that the user won't be mucking about in your namespaces. The example below is a variant on the technique @PieterP posted here. The library provides a single instance of the class. Because the constructor is private, and the copy-constructor and operator= are deleted, it's impossible for the user to instantiate any others.
MySingletonClass.h:
#ifndef MYSINGLETONCLASS_H_
#define MYSINGLETONCLASS_H_
#include "Arduino.h"
class MySingletonClass {
public:
MySingletonClass(const MySingletonClass &) = delete; // no copying allowed
MySingletonClass &operator=(const MySingletonClass &) = delete; // no assignment allowed
static MySingletonClass &getInstance(); // Accessor for singleton instance
void examplePublicInstanceFunction();
static void examplePublicClassFunction();
uint8_t examplePublicInstanceVariable {0};
static uint8_t examplePublicClassVariable;
private:
MySingletonClass(); // Constructor is private
void examplePrivateInstanceFunction();
static void examplePrivateClassFunction();
uint8_t examplePrivateInstanceVariable {0};
static uint8_t examplePrivateClassVariable;
};
extern MySingletonClass &singleton;
#endif /* MYSINGLETONCLASS_H_ */
MySingletonClass.cpp:
#include "MySingletonClass.h"
uint8_t MySingletonClass::examplePrivateClassVariable { 0 };
uint8_t MySingletonClass::examplePublicClassVariable { 0 };
MySingletonClass::MySingletonClass() { // Private constructor
}
MySingletonClass & MySingletonClass::getInstance() {
static MySingletonClass instance;
return instance;
}
void MySingletonClass::examplePublicInstanceFunction() {
}
void MySingletonClass::examplePublicClassFunction() {
}
void MySingletonClass::examplePrivateInstanceFunction() {
}
void MySingletonClass::examplePrivateClassFunction() {
}
MySingletonClass &singleton {MySingletonClass::getInstance()};
The main .ino file uses the one (and only possible) instance of the class named "singleton":
#include "Arduino.h"
#include "MySingletonClass.h"
void setup() {
singleton.examplePublicClassVariable = 100;
singleton.examplePublicInstanceVariable = 200;
singleton.examplePublicInstanceFunction();
singleton.examplePublicClassFunction();
}
void loop() {
}