Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code (PillDispenser.h):

class PillDispenser {
public:
    explicit PillDispenser(BLEAddress deviceAddress);

private:
    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());
    scanner->setInterval(SCAN_INTERVAL);
    scanner->setWindow(SCAN_WINDOW);
    scanner->setActiveScan(true);
    scanner->start(SCAN_DURATION);
}

Issue:
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&

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading