0
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.

NikBond
  • 743
  • 1
  • 5
  • 20
  • 2
    Please provide a [mcve]. Be sure to show all declarations that are needed to compile your code example. – Code-Apprentice Oct 03 '18 at 15:53
  • Might be related: https://stackoverflow.com/questions/274626/what-is-object-slicing – Algirdas Preidžius Oct 03 '18 at 15:57
  • You can pass one, but not an array of them. An array of `PollSocket` is not an array of `pollfd`. – molbdnilo Oct 03 '18 at 15:57
  • You should look at how poll() works : [poll](http://man7.org/linux/man-pages/man2/poll.2.html). The layouts of memory are not the same (pollfd[] vs PollSocket[] ), so that your program works with 1 PollSocket but bugs if 2 or more. – tunglt Oct 03 '18 at 16:03
  • 1
    @Code-Apprentice the question is pretty clear the way it is, I'd disagree with the need for more code. I am also uncertain why the question was downvoted. – SergeyA Oct 03 '18 at 16:10
  • @SergeyA Specifically, I was wondering about the signature for `poll()`. – Code-Apprentice Oct 03 '18 at 16:14
  • 1
    @Code-Apprentice this is a Posix function, so it's signature is well-known. – SergeyA Oct 03 '18 at 17:31

1 Answers1

2

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.

SergeyA
  • 61,605
  • 5
  • 78
  • 137