Function Overloading:
This can achieve at compile time.
It provide multiple definition of the function by changing the signature i.e change the number of parameter, change datatype of parameter .
Return type can not play any role.
Example:
// Function Overloading
#include <iostream>
using namespace std;
//overloaded functions
void test(int);
void test(float);
void test(int, float);
int main()
{
int a = 5;
float b = 5.5;
// Overloaded functions with different type and number of //parameters
test(a);
test(b);
test(a, b);
return 0;
}
// Method 1
void test(int var)
{
cout << "Integer number: " << var << endl;
}
// Method 2
void test(float var)
{
cout << "Float number: "<< var << endl;
}
// Method 3
void test(int var1, float var2)
{
cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}
Output:
Integer number: 5
Float number: 5.5
Integer number: 5 and float number:5.5
Function Overriding:
It can achieved at run time.
Basically it is the features of c++ which can allow us to use and redefine a function in child class which is already declare in the base class. with the same signature.
// Function Overriding
#include<iostream>
using namespace std;
class BaseClass
{
public:
virtual void Display()
{
cout << "\nThis is Display() method"
" of BaseClass";
}
void Show()
{
cout << "\nThis is Show() method "
"of BaseClass";
}
};
class DerivedClass : public BaseClass
{
public:
// Overriding method - new working of
// base class's display method
void Display()
{
cout << "\nThis is Display() method"
" of DerivedClass";
}
};
// Driver code
int main()
{
DerivedClass dr;
BaseClass &bs = dr;
bs.Display();
dr.Show();
}
Output:
This is Display() method of DerivedClass
This is Show() method of BaseClass
Overriding of function can occur when one class can inherited from the other class.
overriding can come into picture when derived class want to added the new job in the predefine function(define in the base class) without changing the signature of the function i.e number of argument, change in datatype of parameter.
Top comments (1)
You should really use
double
and notfloat
. (Floating-point literals like2.0
are of typedouble
anyway.) The only time you should usefloat
is if you have either astruct
containing afloat
or an array offloat
and you have a lot of them to the point where you really need to conserve memory.In
DerivedClass
, you should really declareDisplay()
like:then it's obvious to both the compiler and the human reader that the function is overriding one in the base class. See here for more information.