why do we need to close the old file descriptor
You don't really need to; the example mainly shows that you can. However, each process on a Unix system has a limited number of file descriptors at its disposal, and when you have two of them referring to the same file, one of them is unnecessary so you might as well close it.
Since "out" descriptor is closed now, how does a message sent to stdout_fileno gets written to "out" as well.
Because after the dup2
, STDOUT_FILENO
refers to that file as well, and closing an fd does not close its clones.