Exercice 115
Énoncé
Quels résultats produira ce programme :
#include
using namespace std ;
class point
{ protected : // pour que x et y soient accessibles à pointcol
int x, y ;
public :
point (int abs=0, int ord=0) { x=abs ; y=ord ; }
virtual void affiche ()
{ cout << "Je suis un point \n" ;
cout << " mes coordonnées sont : " << x << " " << y << "\n" ;
}
} ;
class pointcol : public point
{ short couleur ;
public :
pointcol (int abs=0, int ord=0, short cl=1) : point (abs, ord)
{ couleur = cl ;
}
void affiche ()
{ cout << "Je suis un point coloré \n" ;
cout << " mes coordonnées sont : " << x << " " << y ;
cout << " et ma couleur est : " << couleur << "\n" ;
}
} ;
main()
{
point p(3,5) ; point * adp = &p ;
pointcol pc (8,6,2) ; pointcol * adpc = &pc ;
adp->affiche () ; adpc->affiche () ; // instructions 1
cout << "-----------------\n" ;
adp = adpc ;
adp->affiche () ; adpc->affiche () ; // instructions 2
}
Dans les instructions 1, adp (de type point *) pointe sur un objet de type point, tandis que
adpc (de type pointcol *) pointe sur un objet de type pointcol. Il y a appel de la fonction
affiche, respectivement de point et de pointcol ; l’existence du « typage dynamique »
n’apparaît pas clairement puisque, même en son absence (c’est-à-dire si la fonction
affiche n’avait pas été déclarée virtuelle), on aurait obtenu le même résultat.
En revanche, dans les instructions 2, adp (de type point *) pointe maintenant sur un objet
de type pointcol. Grâce au typage dynamique, adp->affiche() appelle bien la fonction
affiche du type pointcol.
276
Précédent

- 277/398

Suivant