Magnesium (Mg) and Copper (Cu) have different reactivities related to their respective tendencies to form cations. Copper's valence electrons are attracted more strongly to the nucleus than Magnesium's, so Magnesium has a greater tendency to form cations (positive ions), by losing electrons to non-metallic elements.
In your reaction, you place Mg in CuO and the Mg replaces Cu, yielding Cu, and MgO. The Mg atoms more readily give up their electrons than Cu atoms so the Cu cations pick up the Mg electrons and become Cu atoms. Since they lost their electrons the Mg atoms have become Mg cations, and are attracted to the O anions forming Magnesium oxide.