2

I there a way to access a struct that has not been declared yet?

//Need to some how declare 'monitor' up here, with out moving 'monitor' above 'device'
//because both structs need to be able to access each others members

struct{
    int ID = 10;
    int Get__Monitor__ID(){
        return monitor.ID; //obvioulsly 'monitor' is not declared yet, therefore throws error and is not accessible
    }
} device;

struct{
    int ID = 6;
    int Get__Device__ID(){
        return device.ID; //because 'device' is declared above this struct, the ID member is accessible
    }
} monitor;
tadman
  • 208,517
  • 23
  • 234
  • 262
Zachwuzhere
  • 329
  • 3
  • 12
  • 1
    You probably mean `struct device { ... }` – tadman Feb 13 '21 at 23:19
  • 1
    Do not tag C for C++ questions. (I presume your code is C++ since C does not provide for function definitions inside structures.) – Eric Postpischil Feb 13 '21 at 23:19
  • Does this answer your question? [Separating class code into a header and cpp file](https://stackoverflow.com/questions/9579930/separating-class-code-into-a-header-and-cpp-file) – 273K Feb 13 '21 at 23:22
  • This design is suspicious. Both classes assumes that they works with a single object of the other type. As soon as the application has 2 monitors or 2 devices, the design is broken. – Phil1970 Feb 13 '21 at 23:30
  • `Get__Monitor__ID` That identifier is reserved for the language implementation. You should use another function name. – eerorika Feb 14 '21 at 01:47

1 Answers1

5

In this particular case, you can define the function prototype in the struct, and the definition can come later.

struct device_t {
    int ID = 10;
    int Get__Monitor__ID();
} device;

struct monitor_t {
    int ID = 6;
    int Get__Device__ID();
} monitor;

int device_t::Get__Monitor__ID() {
  return monitor.ID;
}

int monitor_t::Get__Device__ID() {
  return device.ID;
}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 3
    You probably want to add `inline` unless the functions are moved to CPP file. And only first fonction need to be modified. – Phil1970 Feb 13 '21 at 23:24