David, after being confronted by the prophet Nathan, confessed his sin and was forgiven by God. He was no longer going to die. However, it was already too late to reverse some of the consequences of what he had done. Achieving forgiveness never meant that we can escape the pain of our sins. When we are impatient with each other, we cause hurt. When we lie to each other, we cause mistrust. When we are violent towards each other, we cause pain. Forgiveness heals wounds; it doesn't prevent them.
David's child was blameless and a nameless victim of sin. Sin hurts. It hurts your friends. It hurts your family. It hurts your dog. However, it doesn't hurt God (Job 35:6,8). That bears repeating: your sin does NOT hurt God. He doesn't break down and cry. He is not frustrated or impatient. He fixes it. He cares, however, when people scorn his love and when people despise him because of what his followers do. David showed contempt for God through disobedience and God took corrective action. The world was created to function a certain way with God at the center. Any deviation causes dysfunction and discord. What the Lord does is simply maintenance and repairs.