2.7.1 Surcharger le constructeur

Nous allons pouvoir faire plusieurs constructeurs, suivant les paramètres que l'on veut passer.

Comme nous allons créer plusieurs fonctions, faisant globalement la même chose, nous allons créer une fonction d’initialisation pour notre Shadok (je ne vous en ai pas encore parler mais c'est plus propre de faire comme ça).

Écrivons le prototype de la fonction d'initialisation (dans le private de la classe, on ne va pas s'en servir ailleurs, fichier shadok.h) :

1
void initialisationShadok(const std::string & nom, unsigned int age, ShadokOption::Type type);

Et l'implémentation dans shadok.cpp :

1
2
3
4
5
void Shadok::initialisationShadok(const std::string & nom, unsigned int age, ShadokOption::Type type){
	p_nom = nom;
	p_age = age;
	p_type = type;
}

Maintenant nous allons devoir changer le constructeur par défaut, pour qu'il utilise cette nouvelle fonction (dans shadok.cpp) :

1
2
3
Shadok::Shadok(){
	initialisationShadok("", 0, ShadokOption::SHADOKDUHAUT);
}

Nous pouvons écrire trois constructeurs pour prendre en compte les différents attributs de la classe :

1
2
3
Shadok(const std::string & nom);
Shadok(const std::string & nom, unsigned int age);
Shadok(const std::string & nom, unsigned int age, ShadokOption::Type type);

Là, nous n'en avons que trois, mais on pourrait en faire plus :

1
2
3
4
5
6
7
Shadok(const std::string & nom);
Shadok(unsigned int age);
Shadok(ShadokOption::Type type);
Shadok(const std::string & nom, unsigned int age);
Shadok(const std::string & nom, ShadokOption::Type type);
Shadok(unsigned int age, ShadokOption::Type type);
Shadok(const std::string & nom, unsigned int age, ShadokOption::Type type);

Je vous laisse le soin de les faire si vous avez envie, ça ne peut que vous aider.

Nous allons quand même implémenter nous trois nouveaux constructeurs :

1
2
3
4
5
6
7
8
9
10
11
Shadok::Shadok(const std::string & nom){
	initialisationShadok(nom, 0, ShadokOption::SHADOKDUHAUT);
}

Shadok::Shadok(const std::string & nom, unsigned int age){
	initialisationShadok(nom, age, ShadokOption::SHADOKDUHAUT);
}

Shadok::Shadok(const std::string & nom, unsigned int age, ShadokOption::Type type){
	initialisationShadok(nom, age, type);
}

Voilà pour ce qui est de la surcharge des constructeurs.