Home > Net >  Cpp Instance in Instance in... existance
Cpp Instance in Instance in... existance

Time:02-21

I have some classes in hierarchy. So let's call first class Hardware, it recieves and sends data and each Instance of it wll have some unique parameters. Let it be:

class Hardware{
  private:
    SPI_TypeDef** Instance; 
    GPIO_Port* Port;
    GPIO_Pin Pin;
    int Settings;
  public
    Hardware();
    Hardware(GPIO_Port* Port, GPIO_Pin Pin, SPI_HandleTypeDef* SPIx);
    void TXRX_Data(Byte* TxBuf, Byte* RxBuf, int Length);
};

Then I have class, that controls external device,each device has its own CS (as it is SPI):

class Device{
    private: 
       Hardware Sender;
       Byte Parameter_Buffer;
    public: 
       Device();
       Device(GPIO_Port* Port, GPIO_Pin Pin, SPI_HandleTypeDef* SPIx);
       void SendParameter(Byte Param);
       Byte GetParameter();
};

It's constructor is just

Device::Device(GPIO_Port* Port, GPIO_Pin Pin, SPI_HandleTypeDef* SPIx){
   this->Sender = Hardware(GPIO_Port* Port, GPIO_Pin Pin, SPI_HandleTypeDef* SPIx);
}

And after that all I have the main control class

class DeviceArray{
private:
   Device Devices[DEVICE_QUANTITY];
   Byte Parameters_Buff[DEVICE_QUANTITY];
public:
   DeviceArray();
   DeviceArray(GPIO_Port** Ports, GPIO_Pin* Pins, SPI_HandleTypeDef* SPIx);
   void SendParameters(Byte* Params);
   Byte* GetParameters();
}

It's constructor is:

DeviceArray::DeviceArray(GPIO_Port** Ports, GPIO_Pin* Pins, SPI_HandleTypeDef* SPIx){
    for(uint8_t i = 0;i < DEVICE_QUANTITY; i  ){
         this->Devices[i] = Device(Ports[i], Pins[i],SPIx);
    }  
}

I'll have only one object of this class in my program and it will be global.

And I wonder if instances of Device and their parameters will not be deleted after DeviceArray constructor is closed. And the same is for Hardware (Sender) instances.

The given code is quite abstract, but it is very similar to program I'm trying to make.

CodePudding user response:

And I wonder if instances of Device and their parameters will not be deleted after DeviceArray constructor is closed. And the same is for Hardware (Sender) instances.

Yes, instances of the two types will be destroyed, but that doesn't matter.

For example the line

this->Devices[i] = Device(Ports[i], Pins[i],SPIx);

creates a temporary Device object which will be destroyed at the end of the statement, but that doesn't matter because before that = will call the implicit move assignment operator of Device which will move the members of the temporary Device object into the this->Devices[i] object.

  • Related