vendredi 30 octobre 2015

How to delete a object that attached another object in C++?

I'm working on this unit testing. I feel like to delete the both drill and battery, but it seems doesn't work (battery cannot be deleted maybe). Can I do anything on the destructor so as to deal with this issue?

 void test_rover::testDisconnectBattery() {
        Drill* drill = new Drill();
        drill->connectBattery(new Battery(10));
        drill->disconnectBattery();

        //CPPUNIT_ASSERT(drill->Connected()==false);
        delete drill;
        CPPUNIT_ASSERT(Object::getCount()==0);
    }

Device.cpp (Device is the base of drill)

    Device::Device() {
    }

    Device::Device(const Device& copy) {
    }

    Device::~Device() {
       delete _battery;
    }

    void Device::connectBattery(Battery *b){ 
        _battery = b;
    }

    void Device::disconnectBattery(){
        _battery = NULL;
    }

Battery.cpp

Battery::Battery(int power) {
    _power = power;
}

Battery::Battery(const Battery& copy) {
}

Battery::~Battery() {
}

int Battery::Power(){
    return _power;
}

Aucun commentaire:

Enregistrer un commentaire