Search code examples
c++inheritancesystem-callspolling

Passing inherited structs to poll()


class Socket{ //implementation
};

struct PollSocket : pollfd  {
     Socket mSocket;
     // some methods
}

std::vector<PollSocket> mPolledSockets;
poll(mPolledSockets.data(), mPolledSockets.size(), 0);

Can I pass inherited structs to poll()? If not, why? It seems I get a lot of bugs in such case.


Solution

  • You can't treat an array (or vector) of objects polymorphically, and this question is not specific to poll mechanism.

    The reason is rather simple - if the function expects a pointer to N objects, each of which has size Z, and you pass it an array of N objects each of which has size Z1, the function will be very confused - it would expect the second object to begin at offset Z, while instead it would begin at offset Z1. Of course, it will lead to all sort of troubles.

    The situation would be different, if function expected the array of pointers to objects - this would work.