Initializing Struct Reference

Status
Not open for further replies.

neroroxxx

Well-known member
Hi guys, i'm trying to figure out if this is possible.

I have a 2 classes, one of them contains a large struct i want to create a reference to that struct on another class.

Basically i want class A to have a reference of the struct stored in class B, obviously the code below doesn't work and generates an error since "ref" was never initialized, is there a way to do this? if so what's the proper way?

Code:
struct dataStruct {
  uint8_t data;
};


class A {
  public:
    A():b(ref){
    
    }
  private:
    B b;
    dataStruct& ref;
};


class B {
  public:
    B(dataStruct& ref){
      ref = data;
    }
  private:
    dataStruct data;
};
 
What you're trying to do seems quite convoluted and I can't imagine a reason for doing it. But, at least this compiles:
Code:
#include <Arduino.h>

struct dataStruct {
  uint8_t data;
};

class B {
  friend class A;
  public:
    B() {}

  private:
    dataStruct data;
};

class A {
  public:
    A(): ref(b.data) {}
   
  private:
    B b;
    dataStruct& ref;
};

A objectA;

void setup() {}

void loop() {}
 
Status
Not open for further replies.
Back
Top