So, how does C++ compiler differentiate those two methods? C++ compiler observes the amount, data type and argument sequence. It’s clear that the compiler use parameters to differentiate methods which have the same name. Not differentiate them with their return type.
To make method overloading, we need at least one of these three conditions below;
- have different argument amount
- have different argument data type
- have different argument sequence
[sourcecode language='cpp']// method multiply with two arguments (number1 dan number2)
int multiply(int number1, int number2) {
return number1*number2
}[/sourcecode]
// method multiply with three arguments (number1, number2 dan number3)
int multiply(int number1, int number2, int number3) {
return number1*number2*number3;
}
Method multiply above are VALID because they have different argument amount.
Example #2 (different argument data type):
// method showGrade has a char data type argument
void showGrade(char grade) {
cout << "Grade (in letter): " << grade;
}
// method showGrade has a int data type argument
void showGrade(int grade) {
cout << "Grade (in number): " << grade;
}
Method showGrade above are VALID because they have different data type argument although they have the same argument amount.
Example #3 (different argument sequence):
// method multiply with data type number1 is int
// and number2 is double
double multiply(int number1, double number2) {
return number1*number2;
}
// method multiply with data type number1 is double
// and number2 is int
double multiply(double number1, int number2) {
return number1*number2;
}
Those method above are VALID because they have different argument sequence. In the first multiply method, number1 has int data type then number2 has double data type. In the second method, number1 has double data type and number2 has int data type.
REMEMBER!!!
Frequently mistake done by the programmer is assigning the same amount or sequence argument with the different return type. It will return SYNTAX ERROR while compiling it.
Wrong example:
// return type: int
int countAge(int age) {
return age + 2;
}
// return type: void
void countAge(int age) {
cout<<"Student age after two years = "<<age+2;
}
SYNTAX ERROR. Method can’t be overloaded because they have same argument amount with the same data type.
No related posts.








Leave a Reply