I wish to access methods and fields, as well as change them, of class A from class B. Since the main Arduino sketch is not a class, but a list of fields and methods, I created a separate MainClass with a method printStuff() that I want to call from class DoClass. This is how I go about it:
The main sketch:
#include "MainClass.h"
MainClass m;
void setup() {
m.setup();
}
void loop() {
m.loop();
}
MainClass.h:
/*
MainClass.h
*/
#ifndef MainClass_h
#define MainClass_h
#include "Arduino.h"
class MainClass
{
public:
MainClass();
void setup();
void loop();
void printStuff();
};
#endif
MainClass.cpp:
/*
MainClass.cpp
*/
#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"
MainClass::MainClass()
{
d DoClass(this);
}
void MainClass::setup(){
Serial.begin(9600);
}
void MainClass::loop(){
d.callMainClassFunct();
}
void MainClass::printStuff(){
Serial.println("printing stuff");
}
DoClass.h:
/*
DoClass.h
*/
#ifndef DoClass_h
#define DoClass_h
#include "Arduino.h"
#include "MainClass.h"
class DoClass
{
public:
DoClass(MainClass m);
void callMainClassFunct();
private:
MainClass _m;
};
#endif
DoClass.cpp:
/*
DoClass.cpp
*/
#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"
DoClass::DoClass(MainClass m)
{
_m = m;
}
void DoClass::callMainClassFunct(){
_m.printStuff();
}
This produces a myriad of errors. Each time I change something, a new kind of error appears, as though I was in a vicious cycle. Clearly, I am unfamiliar with C++. It would greatly help me if you could alter my code so that it works, keeping in mind that I would like to both access methods and fields of class MainClass from class DoClass and change those fields from class DoClass.
For reference, in Java, I would achieve the same in the following way:
MainClass.java:
public class MainClass{
DoClass d;
public MainClass(){
d = new DoClass(this);
}
public void setup(){
}
public void loop(){
d.callMainClassFunct();
}
public void printStuff(){
Serial.println("print stuff");
}
}
DoClass.java:
public class DoClass{
MainClass _m;
public DoClass(MainClass m){
_m = m;
}
public callMainClassFunct(){
_m.printStuff();
}
}
Passing this to the constructor od DoClass passes the value of the reference pointing to MainClass instantitated in the main sketch file. Then, by prepending the name of the instantiated object (in this case, "m"), followed by a dot, I can simply access and change all values of that object from DoClass (provided those methods and fields are visible to DoClass, which is the case here).
I have posted before about this issue, but did not receive any answers to my specific question and could not comment because I do not have enough reputation. Thank you to those who tried to answer me, but the answers did not pertain to my specific question. This time I have included more information to show my problem more clearly. Thank you in advance for your help.