Differentiate between function overriding and function overloading.
If a program can be written using function overloading and using default arguments,which one is preferable?Explain giving example.
Write overloaded functions to find the area of scalene,isosceles and equilateral triangle.
Area of scalene triangle = √(s(s-a)(a-b)(s-c))
Area of isosceles triangle = ½[√(a2 − b2 ⁄4) × b]
Area of equilateral triangle= (√3/4)a2
Overriding of functions occur than the function with the same signature is defined in a derived and a base class. So it relates to the class inheritance only.
Overloading of functions occur than there are two functions with the same name, but the different number and/or types of parameters, that it's they have different signatures.
If a program can be written using function overloading and using default arguments, it is preferable to use default arguments as in this case one should support only one function instead of several.
Example:
Instead of having two functions for drawing common circles and unit circles
void DrawCircle(double x_c, double x_y, double r);
void DrawCircle((double x_c, double x_y);
it is more convenient to have only one function
void DrawCircle(double x_c, double x_y, double r=1.0);
Functions for area calculations:
// scalene triangle
double TriangleArea(double a, double b, double c) {
double s = a+b+c;
return sqrt(s*(s-a)*(s-b)*(s-c));
}
// isosceles triangle
double TriangleArea(double a, double b) {
return sqrt(a*a-b*b/4)*b/2;
}
// equilateral triangle
double TriangleArea(double a) {
return sqrt(3)*a*a/4;
}
Comments
Leave a comment