Custom CObject subclasses holding references to an instance of the other's class

 

I've created 2 custom classes that need to be able to hold a reference to an instance of the other's class.

They've been created with the MQL4 class template.

I broke them down to the basics.

Candle class:

#include <Arrays/ArrayObj.mqh>
#include "MyTrade.mqh"

class MyCandle: public CObject {
public:
   MyTrade *trade;
  
   MyCandle();
   MyCandle(MyTrade *_trade);
  
   ~MyCandle();
};

MyCandle::MyCandle() {}

MyCandle::MyCandle(MyTrade *_trade) {
   trade = _trade;
}

MyCandle::~MyCandle() {}

Trade class:

#include <Arrays/ArrayObj.mqh>
#include "MyCandle.mqh"

class MyTrade: public CObject {
public:
   MyCandle *candle;
  
   MyTrade();
   MyTrade(MyCandle *_candle);
  
   ~MyTrade();
};

MyTrade::MyTrade() {}

MyTrade::MyTrade(MyCandle *_candle) {
   candle = _candle;
}

MyTrade::~MyTrade() {}


The compiler will give several complaints:

'MyTrade' - declaration without type    MyCandle.mqh    27    20

'*' - comma expected    MyCandle.mqh    27    28

'MyTrade' - identifier already used    MyCandle.mqh    27    20

see previous declaration of 'MyTrade'    MyTrade.mqh    17    7

'trade' - undeclared identifier    MyCandle.mqh    28    4

'_trade' - undeclared identifier    MyCandle.mqh    28    12


Any help to fix this much appreciated, I'm willing to learn.


I'm usually able to iron out errors but it's the first time I've been digging deeper into C++ and MQL4 custom classes / arrays.


Unfortunately I can't find any indicators that make use of custom classes to learn from, so if you know any, it would be great if you could point me to them.

 
Your classes are mutually dependent, you need forward declaration for one of them
 
Vadim Larionov:
Your classes are mutually dependent, you need forward declaration for one of them

Thank you for the reply. Could you please give an example for that?

I thought the parametric constructor with the assignment would be sufficient.

The reason I was "outsourcing" the classes into their own files in the first place was that the type of one of the classes wouldn't be recognised by the compiler as it was declared later in the file. When I would change the order of their declaration the 2nd class would not be available in the 1st one.

Everything else, other properties of these classes that I had defined, would be working fine.

 
Vadim Larionov:
Your classes are mutually dependent, you need forward declaration for one of them

I've looked here: https://www.mql5.com/en/forum/1526

And simply added "class MyTrade;" to the MyCandle file outside the class and did the same with the MyTrade class in the other file.

With both declarations the errors are gone. Is that it?


Also, the linked thread was from July 2010, forward declaration didn't seem to be available back then (as mentioned there).

I guess it has been implemented since then.

Thanks again for your advice.

Reason: