C plus plus (c++) provide overloading and overriding function :
- Overloading
- have the same function name
- exit in the same class( if have class)
- difference signature (type or number parameter)
- allow more than definition for a function name
Example :
// www.learning2night.com
#include <iostream>
using namespace std;
int sum(int a,int b){
return a+b;
}
int sum(int a,int b,int c){
return a+b+c;
}
float sum(float a, float b){
return a+b;
}
double sum(double a, double b){
return a+b;
}
int main(){
cout<<"sum int "<<sum(1,2)<<endl;
cout<<"sum int 3 parameters "<<sum(1,2,3)<<endl;
cout<<"sum double "<<sum(1.0D,2.0D)<<endl;
cout<<"sum float "<<sum(1.0,2.0)<<endl;
return 0;
}
Output:
sum int 3 sum int 3 parameters 6 sum double 3 sum float 3
- Overriding
- have the same function name and signature
- exit in inheritance
- must be done in class
- child class override function of parent(s) class
Example:
// www.learning2night.com
#include<iostream>
using namespace std;
class Base{
public:
void display(){
cout<<"Parent Class "<<endl;
}
};
class Derived: public Base{
public:
// override function
void display(){
cout<<"child class "<<endl;
}
};
int main(){
Derived d;
d.display();
return 0;
}
Output:
child class