(Teachings from Gita) When a man is nearing his end, he gets to whatever he'd been thinking of in those last moments. Thus, if you think of God then you'll be united with Him. If you were thinking of your house, you'll be born in your house. However, the form in which you'll be born will be decided by your deeds in this birth. For example, a man living in a house thinks its his house. The ants living in that house also think that its their house.
What does a man think of in his last moments? Mostly, you think of those things that you've spent most of your life thinking. Depending on your environment, education, interests etc., your mind may be impressed with certain things. It could be desire for a house, family or anything else. These thoughts which occupy your mind most of your life are also the ones that linger in your mind in your last moments because you've exercised them for so long. However, you can substitute these thoughts with some other with practice. If you want to escape this viscious cycle of life and death, then you must think of God and only God in those moments.
P.S.: This chapter in Gita which talks about death is the most difficult to grasp and hence the long gap in my posts on Gita.