Storing a reference to an object within class

Hi, I have been searching a lot for this one, but somehow I just can't get it right..

I want to store a reference to an object inside another object. In my example, I store the first class in the second and changes a variable in the main. But when I print the variable of the object in the second class afterward, it has not changed.

My setup is as following..

The main:

#include "mySecondClass.h"
#include "myClass.h"

myClass obj;
mySecondClass obj2;

void setup() {
Serial.begin(9600);

obj.testN = 5;
obj2.setObj(obj);

obj.testN = 10;
Serial.println(obj2.myClassObj.testN);
}

the first class header

// myClass.h

#ifndef _MYCLASS_h
#define _MYCLASS_h

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

class myClass
{
protected:

public:
void init();
int testN = 0;
};

extern myClass my;

#endif

the second class header

// mySecondClass.h
#include "myClass.h"
#ifndef _MYSECONDCLASS_h
#define _MYSECONDCLASS_h

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

class mySecondClass
{
protected:

public:
void init();
void setObj(myClass &obj);
myClass &myClassObj;
};

extern mySecondClass mySecond;

#endif

the second class cpp

#include "mySecondClass.h"
#include "myClass.h"
void mySecondClass::init()
{
}

void mySecondClass::setObj(myClass &obj)
{
myClassObj = obj;
}
mySecondClass mySecond;

I can't think of a good reason to store a reference in a class (difficult to write a copy-constructor is the first thing that springs to mind).

Can you explain your intentions?

Please remember to use code tags when posting code.

Store a pointer instead?

gfvalvo:
Store a pointer instead?

++

So things like this:

myClass &myClassObj;

References can only be assigned when constructing an object, and cannot be modified after that.

use pointers

MyClass *myClassObj;

void setObj(MyClass *obj);

obj2.setObj(&obj);

Serial.println(obj2.myClassObj->testN);

Thank you so much :slight_smile: I ended up doing:

----- header ------
class mySecondClass
{

public:
myClass *myClassObj;

void init();
void setObj(myClass &obj);

};

----- cpp ------

void mySecondClass::setObj(myClass &obj)
{
myClassObj = &obj;
}

------ main ------

void setup() {
Serial.begin(9600);

obj.testN = 5;
obj2.setObj(obj);

obj.init = 10;
Serial.println(obj2.myClassObj->testN);
}