Home > Net >  Passing objects of different derived class as a parameter to a function that expects base object of
Passing objects of different derived class as a parameter to a function that expects base object of

Time:11-21

I have a base class Device and inherited class InputDevice. In class XYZ I have a function XYZ::setDevice(int num, Device device) that expects object Device as parameter. When I call the function setDevice() with parameter that is sublclass of Device (InputDevice) it gets converted to Device and I can't access the derived functions of derived class afterwards. So if I want to call the function of "device" in function setDevice() it calls function of Device instead of overriden function in class InputDevice. What am I doing wrong?

void XYZ::setDevice(int num, Device device) {

    printf("%s\n", typeid(device).name());                    //this prints "Device"
    this->devices[num] = device;
}

XYZ::XYZ() {
    printf("%s\n", typeid(InputDevice(cin)).name());          //this prints "InputDevice"

    setDevice(STANDARD_INPUT_DEVICE, InputDevice(cin));
    printf("%s\n", typeid(devices[0]).name());
}

CodePudding user response:

I don't see the full code, but instead of storing objects, you should store pointers. Your devices array should be vector or array of Device pointers.

Here's a fully working example.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Device {
public:
    virtual string getName() const {
        return string("Device");
    }
};

class InputDevice : public Device {
public:
    string getName() const override{
        return string("InputDevice");
    }
};

class XYZ {
    Device* devices[10];

public:

    void setDevice(int num, Device *device)
    {
        devices[num] = device;
        cout << "Name : " << device->getName();
    }

};

int main()
{
    Device* dev1 = new Device();
    Device* dev2 = new Device();
    InputDevice* dev3 = new InputDevice();
    XYZ xyz;
    xyz.setDevice(0, dev1);
    xyz.setDevice(1, dev2);
    xyz.setDevice(2, dev3);
}
  • Related