Initializing a new nested class from outer class function

I’m currently learning nested classes in C++ while building a project and I currently inside setupBLE() I need to pass one of the nested classes but to init that new class I need to pass to its constructor the outer class so it can access its variables and functions but I’m not exactly sure how to pass to the constructor the pointer of the class that’s trying to create it.

It’s a bit confusing so I hope the code helps with it.

Like in python we have self but in C++ as far as I know we don’t have that so I was wondering what should I pass to the constructor.

Code (PillDispenser.h):

class PillDispenser {
    explicit PillDispenser(BLEAddress deviceAddress);

    BLEAddress _device_address;
    BLEAdvertisedDevice _device;
    bool _connected;
    // Device properties
    std::string _device_name;

    // Callbacks
    static void notifyCallBack();

    class AdvertisedDeviceCallBack : public BLEAdvertisedDeviceCallbacks {
        PillDispenser &_outer;

        explicit AdvertisedDeviceCallBack(PillDispenser &outer) : _outer(outer){};

        void onResult(BLEAdvertisedDevice advertisedDevice) override;

Code (PillDispenser.cpp):

void PillDispenser::setupBLE() {
    BLEScan *scanner = BLEDevice::getScan();
    scanner->setAdvertisedDeviceCallbacks(new AdvertisedDeviceCallBack());

enter image description here

>Solution :

This line is trying to use the default constructor which does not exist

scanner->setAdvertisedDeviceCallbacks(new AdvertisedDeviceCallBack());

instead you should use the explicit constructor you defined

scanner->setAdvertisedDeviceCallbacks(new AdvertisedDeviceCallBack(*this));

note that this (in this context) has type PillDispenser* so you have to dereference with * to get a PillDispenser&

Leave a Reply