Functions in C ++: overloading and default settings
In C++, the same function or class method can be overloaded, and we can have what are called default settings. This feature is also valid for class constructors.
When you overload a function, we declare it two or more times, keeping the same name, and the same return type. Changing the return type would correspond to polymorphism.
Example: Polygone.hpp
#include
This example illustrates the declaration of the Polygone class using the constructor overload and the setTaille() function.
As for Polygonepp:
#include "polygone.hpp" using namespace std; Polygone::Polygone() { cout << endl << "Je suis un polygone, mais je ne sais pas si je suis regulier, ni combien j'ai de cotes, ni leur taille." << endl; } Polygone::Polygone(int nombreCote) { cout<< endl << "Je suis un polygone a " << nombreCote << " cotes mais je ne connait pas leur taille, et je ne sais pas si je suis regulier." << endl; sonNombreCote = nombreCote; } Polygone::Polygone(int nombreCote, bool regulier) { cout << endl << "Je suis un polygone a " << nombreCote << " cotes mais je ne connait pas leur taille."; if(regulier == true) cout << " Je suis regulier !" << endl; else cout << " Je ne suis pas regulier." << endl; sonNombreCote = nombreCote; regulier = true; }
In this example, we shall see the implementation of overloaded methods.
You can test the two files with mainpp:
#include "polygone.hpp" #include
The use of the default settings can be useful when you do not know the value certain parameters, while a function is waiting for them.
When making the declaration, the default settings should be at the far right.
Example: redefining the setTaille function:
void setTaille(int tailleCote1 = 5, int tailleCote2 = 8, int tailleCote3 = 4) { cout << "Je connait la taille de mon premier cote : il mesure " << tailleCote1 << " cm." << endl; cout << "Je connait la taille de mon deuxieme cote : il mesure " << tailleCote2 << " cm." << endl; cout << "Je connait la taille de mon troisieme cote : il mesure " << tailleCote3 << " cm." << endl; saTailleCote1 = tailleCote1; saTailleCote2 = tailleCote2; saTailleCote3 = tailleCote3; }
This is remarkably simple. Using mainpp:
#include "polygone.hpp" using namespace std; int main(int argc, char *argv[]) { cout << endl << "Polygone simple : "; Polygone polygoneSimple; cout << endl << "Polygone a trois cotes : "; Polygone polygoneATroisCotes(3); cout << endl << "Polygone a 7 cotes : "; Polygone polygoneASeptCotesRegulier(7, true); cout << endl << "Polygone simple : "; polygoneSimple.setTaille(); cout << endl << "Polygone a trois cotes : " << endl; polygoneATroisCotes.setTaille(1, 90); cout << endl << "Polygone a 7 cotes : " << endl; polygoneASeptCotesRegulier.setTaille(); cout << endl << endl; system("PAUSE"); return EXIT_SUCCESS; }
You can now test the code.