1

New with C++ but been coding a lot of ObjC back in the day. So i thought i was smart trying to solve a cross reference issue with the old delegate pattern used widely in ObjC but only managed to move the issue it to another file .

Im trying to reach the invoker of the file by passing it as a reference, conforming to a "interface".

#pragma once

#include <libUI.h>
#include <Arduino.h>

class PeripheralDelegate {
public:
    virtual void pushViewController(PeripheralViewController* vc) = 0;
    virtual void popLastViewController() = 0;
};

class PeripheralViewController: public ViewController {
private:
    PeripheralDelegate* mDelegate;
public:
    PeripheralViewController(): ViewController(), mDelegate() {}
    PeripheralViewController(String id, Rect frame, PeripheralDelegate* delegate): ViewController(id, frame), mDelegate(delegate) {}
    virtual ~PeripheralViewController() {}
    virtual void encoderValueChanged(int newVal, int oldVal) = 0;
    virtual void encoderSwitchPressed() = 0;
    virtual void backButtonPressed() = 0;
    virtual void firstButtonPressed() = 0;
    virtual void secondButtonPressed() = 0;
};

Also, all kind of feedback on the code is much appriciated!

Oscar
  • 375
  • 3
  • 15
  • [What are forward declarations and their uses](https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c). – Jason Nov 07 '22 at 13:26

2 Answers2

2

You can predeclare PeripheralViewController and then you can use a pointer to it:

class PeripheralViewController;
lorro
  • 10,687
  • 23
  • 36
2

I often use interfaces to break dependencies (on implementation). And that would work here too. Using interfaces helps writing unit tests too.

#pragma once

#include <libUI.h>
#include <Arduino.h>

class ViewController
{
};

class PeripheralViewControllerItf
{
    // abstract methods here (the ones that PeripheralDelegate needs)
};

class PeripheralDelegate 
{
public:
    virtual void pushViewController(PeripheralViewControllerItf& vc) = 0; // I prefer reference since it shouldn't accept nullptr's 
    virtual void popLastViewController() = 0;
};

class PeripheralViewController : 
    public PeripheralViewControllerItf,
    public ViewController 
{
private:
    PeripheralDelegate* mDelegate;
public:
    PeripheralViewController() : ViewController(), mDelegate() {}
    PeripheralViewController(String id, Rect frame, PeripheralDelegate* delegate) : ViewController(id, frame), mDelegate(delegate) {}
    virtual ~PeripheralViewController() {}
    virtual void encoderValueChanged(int newVal, int oldVal) = 0;
    virtual void encoderSwitchPressed() = 0;
    virtual void backButtonPressed() = 0;
    virtual void firstButtonPressed() = 0;
    virtual void secondButtonPressed() = 0;
};
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19