Function overriding and overloading are forms of Polymorphism in Object Oriented Programming. Method overloading occurs when two or more methods with the same method name but a different number of parameters in a single class. Method overriding means two methods with the same method name and the same number of parameters in two different classes means parent class and child class.
As stated earlier, function overloading means declaring the same function name more than once with different parameters. For example, to find the area of vector, we need to pass radius as a parameter for circle whereas we need to pass length and breadth as parameters for rectangle. In that case, we need to pass one parameter for circle and two parameters for rectangle.
Lets check at the below example:
We have defined two functions
area with within a class
Vector. First one accepts single arguments and second one accepts two arguments. When we initialize the class and call the function name, we will get the error
FATAL ERROR Cannot redeclare Vector::area() on line number 8. Because we have redeclared the same function twice.
This can be overcome using
__call. We accept function name and arguments inside it. Then we write switch cases to handle according to the number of arguments.
This code will output:
Area of Circle: 314.15 Area of Rectangle: 100
Function overriding means both the parent and child classes should have the same function name and the same number of arguments. Function overriding is used to replace the parent method in child class.
The function will output:
Function from Base Class with Base Function from Derived Class : Derived