Professional Documents
Culture Documents
Week 10
Week 10
Week 10
Overriding
Function Overloading
The term ‘overloading’ means a name having two or
more distinct meanings
Thus, an ‘overloaded function’ refers to a function
having (one name and) more than one distinct meanings
Revision - What is Happening Here?
class Rectangle
{
public: int main()
void printArea(int x, int y) {
{ cout << x * y << endl; }
Rectangle rt;
void printArea(int x)
rt.printArea(2,4);
{ cout << x * x << endl; }
rt.printArea(2,5.1);
void printArea(int x, double y)
{ cout << x * y << endl; } rt.printArea(10);
void printArea(double x) rt.printArea(2.3);
{ cout << x * x << endl; } return 0;
}; }
Function Overriding
It is when we define a function with same name and
arguments in both base class and derived class, then
the function s called as overridden function and the
process is called function overriding
It enables programmer to change the behavior of any
base class functionality in the derived class
When you class the overridden function by child
object the child version is called and when your call
the overridden using base class object the base class
version is called
Example
class Animals
{public:
void sound()
{ cout << "This is parent class" << endl; }
};
class Dogs : public Animals
{public:
void sound()
{ cout << "Dogs bark" << endl; }
};
void main()
{ The sound() function in the child
Dogs d; class overrides the sound()
d.sound(); function in the parent class OUTPUT:
} Dogs bark
Condition for Function Overriding
Functions of both parent and child class must have the
same name
Functions must have the same argument list and return
type
If a function cannot be inherited, it cannot be
overridden
NOTE:
Constructors cannot be overridden
Overloading VS Overriding
Inheritance: Overriding of functions occurs when one class is
inherited from another class. Overloading can occur without
inheritance.
Function Signature: Overloaded functions must differ in
function signature i.e. either number of parameters or type of
parameters should differ. In overriding, function signatures must
be same.
Scope of functions: Overridden functions are in different scopes;
whereas overloaded functions are in same scope.
Behavior of functions: Overriding is needed when derived class
function has to do some added or different job than the base class
function. Overloading is used to have same name functions which
behave differently depending upon parameters passed to them.