| 1. |
Explain function overloading and function overriding in the context of C++ programming language. Differentiate between them. |
Answer»
It allows for multiple definitions of the function by modifying the signature, i.e. the number of parameters, the datatype of the parameters, and the return type. For example: using namespace std; // Method 1void overloadedMethod(int x){ cout << "In Overloaded Method 1" << endl;} // Method 2void overloadedMethod(float x){ cout << "In Overloaded Method 2" << endl;} // Method 3void overloadedMethod(int x1, float x2){ cout << "In Overloaded Method 2" << endl;} int main(){ int x = 5; float y = 5.5; overloadedMethod(x); overloadedMethod(y); overloadedMethod(x, y); return 0;}Output: In Overloaded Method 1In Overloaded Method 2In Overloaded Method 3Explanation: In the above code, we have three functions with the same name and return type. However, they have different function SIGNATURES which differentiates them from each other. When we pass a parameter of int type, method 1 gets EXECUTED. When we pass a parameter of float type, method 2 gets executed. When we pass both an int and a float type parameter, method 3 gets executed.
It is the redefining of a base class function in a derived class with the same signature, that is, the return type and parameters. It's only possible in derived CLASSES. class Test{public: virtual void print(){ cout << "Test Function"; }};class Sample : public Test{public: void print(){ cout << "In Sample Function";}};int main(){ Test obj = new Sample(); obj.print(); return 0;}Output: In Sample FunctionIn the above code, the class Sample extends the class Test and therefore inherits all its properties. We can clearly see that both the classes have a function ‘print’ with the same function signature and return type. Therefore, the above code IMPLEMENTS function overriding. Since we have added a virtual keyword in the function of the base class, the function is CALLED according to the type of object being referred to and so the print function of the Sample class gets called. The following points illustrate the differences between function overloading and function overriding:
|
|