Calling child member from Base/Parent array?

So, I have a base class and a child class. Something like

Class Device 
{
     double read();
}

Class Relay : Public Device
{
      void toggleSwitch();
}

Class Sensor : Public Device
{
      int getValue();
}

I have an array to store the objects so I can keep track of them

Device *devices[10];
devices[0] = new Relay();
devices[1] = new Sensor();
etc…


devices[0]->toggleSwitch(); // error

I can call the member read() from any of these devices fine since read() is in the base class. So how do I call toggleSwitch() in Relay? I would get an error saying 'class Device' has no member named 'toggleSwith'. It makes sense since the 'devices' array is of Device. So how do I call a member of the child? I tried casting but it wasn't having it. thanks.

Answers


Another solution is that when you know device[i] is a pointer to Relay then just cast it.

((Relay *)devices[i])->toggleSwitch();

The disadvantage of virtual functions is the added overhead (more memory usage and slower code), but this can get problematic only if you allocate a really a big (millions) amount of instances of your class. You also need to modify the base class (if it's third part code you may don't want that).


You need to use (pure) virtual functions. In your base class, add the following:

virtual void toggleSwitch() = 0; virtual int getValue() = 0;

The above will now result in those virtual functions implemented in your specialisations being able to be called via your base class pointers.


Need Your Help

C# Create Instance of Color from any supported Format (Win.Forms Properties -> Color)

c# colors parsing

What is the best way to instantiate a new Color from any supported value, like for example