Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

Programming in C++

CST-152
UNIT-I
Polymorphism
Chapter-6
Course Objectives
• To gain knowledge of polymorphism and its various types.
• To understand the concept of function overloading and
operator overloading .

University Institute of Engineering


Contents
• Introduction & types of polymorphism
• Function overloading
• Operator overloading
• Overloading of unary & binary operators
• Constructor Overloading.

University Institute of Engineering


Polymorphism
• Polymorphism
• Enables “programming in the general”
• The same invocation can produce “many forms” of results
• When a program invokes a method through a superclass variable,
• the correct subclass version of the method is called,
• based on the type of the reference stored in the superclass
variable
• The same method name and signature can cause different actions to
occur,
• depending on the type of object on which the method is invoked

University Institute of Engineering


Cont..
• Polymorphism enables programmers to deal in generalities and
• let the execution-time environment handle the specifics.
• Programmers can command objects to behave in manners
appropriate to those objects,
• without knowing the types of the objects
• (as long as the objects belong to the same inheritance
hierarchy).

University Institute of Engineering


Types of Polymorphism

There are two types of polymorphism in C++


• Static or Compile time polymorphism
• Dynamic or Run time polymorphism
Static Polymorphism

Static or compile time polymorphism


• In this type of polymorphism behavior of functions and
operators decide at compile time. Thus, it is known as static
or compile time polymorphism.
There are two types of static polymorphism:
• Function overloading
• Operator overloading
Dynamic Polymorphism

• Dynamic or run time polymorphism


• Dynamic polymorphism is basically used for runtime time
member function binding. Thus, it is known as dynamic
polymorphism.
• There are following types of dynamic polymorphism:
• Virtual functions
Here, we are implementing polymorphism (dynamic
polymorphism) using virtual function.
Virtual Functions
class A {
• Used to support polymorphism with pointers and
public:
references
A () {cout<<" A";}
• Declared virtual in a base class
virtual ~A () {cout<<" ~A";}
virtual f(int);
• Can override in derived class
};
• Overriding only happens when signatures are the
same
class B : public A {
• Otherwise it just overloads the function or operator
public: name
B () :A() {cout<<" B";} • More about overloading next lecture
virtual ~B() {cout<<" ~B";} • Ensures derived class function definition is resolved
virtual f(int) override; //C++11 dynamically
}; • E.g., that destructors farther down the hierarchy get
called
int main (int, char *[]) {
// prints "A B" • Use final (C++11) to prevent overriding of a virtual
method
A *ap = new B;
• Use override (C++11) in derived class to ensure that the
// prints "~B ~A" : would only
signatures match (error if not)
// print "~A" if non-virtual
delete ap;
return 0;};
University Institute of Engineering
Cont..
class A {
public:
void x() {cout<<"A::x";}; • Only matter with pointer or reference
virtual void y() {cout<<"A::y";}; • Calls on object itself resolved statically
}; • E.g., b.y();
• Look first at pointer/reference type
class B : public A { • If non-virtual there, resolve statically
public:
• E.g., ap->x();
• If virtual there, resolve dynamically
void x() {cout<<"B::x";};
• E.g., ap->y();
virtual void y() {cout<<"B::y";};
• Note that virtual keyword need not be repeated in
}; derived classes
• But it’s good style to do so
int main () { • Caller can force static resolution of a virtual function
B b; via scope operator
A *ap = &b; B *bp = &b; • E.g., ap->A::y(); prints “A::y”
b.x (); // prints "B::x"
b.y (); // prints "B::y"
bp->x (); // prints "B::x"
bp->y (); // prints "B::y"
ap->x (); // prints "A::x"
ap->y (); // prints "B::y"
return 0;
};

University Institute of Engineering


Potential Problem: Class Slicing

• Catch derived exception types by reference


• Also pass derived types by reference
• Otherwise a temporary variable is created
• Loses original exception’s “dynamic type”
• Results in “the class slicing problem” where only the base class
parts and not derived class parts copy

University Institute of Engineering


Function Overloading
• If any class have multiple functions with same names but
different parameters then they are said to be overloaded.
Function overloading allows you to use the same name for
different functions, to perform, either same or different
functions in the same class.
• Function overloading is usually used to enhance the
readability of the program
Ways to overload a function
• By changing number of Arguments.
• By having different types of argument.

University Institute of Engineering


Number of Arguments different
In this type of function overloading we define two functions with same names but
different number of parameters of the same type. For example, in the below
mentioned program we have made two sum() functions to return sum of two and
three integers.
int sum (int x, int y)
{ cout << x+y;
} int sum(int x, int y, int z)
{ cout << x+y+z; }
• Here sum() function is overloaded, to have two and three arguments. Which sum()
function will be called, depends on the number of arguments.
int main() {
sum (10,20); // sum() with 2 parameter will be called
sum(10,20,30); //sum() with 3 parameter will be called
}

University Institute of Engineering


Different Data type of Arguments

• In this type of overloading we define two or more functions with same name and same
number of parameters, but the type of parameter is different. For example in this program,
we have two sum() function, first one gets two integer arguments and second one gets two
double arguments.
int sum(int x,int y)
{
cout<< x+y;
}
double sum(double x,double y)
{
cout << x+y;
}
int main()
{
sum (10,20);
sum(10.5,20.5);
}

University Institute of Engineering


Operator Overloading

• Operator overloading is an important concept in C++. It is a type of


polymorphism in which an operator is overloaded to give user defined meaning to
it. Overloaded operator is used to perform operation on user-defined data type.
For example '+' operator can be overloaded to perform addition on various data
types, like for Integer, String(concatenation) etc.
• Almost any operator can be overloaded in C++. However there are few operator
which can not be overloaded. Operator that are not overloaded are follows
• scope operator - ::
• sizeof
• member selector - .
• member pointer selector - *
• ternary operator - ?:

University Institute of Engineering


Operator Overloading Syntax

University Institute of Engineering


Implementing Operator Overloading

Operator overloading can be done by implementing a function


which can be :
• Member Function
• Non-Member Function
• Friend Function
Operator overloading function can be a member function if the
Left operand is an Object of that class, but if the Left
operand is different, then Operator overloading function
must be a non-member function.
Operator overloading function can be made friend function if it
needs access to the private and protected members of class.

University Institute of Engineering


Overloading Arithmetic Operator

• Arithmetic operator are most commonly used operator in C++.


Almost all arithmetic operator can be overloaded to perform
arithmetic operation on user-defined data type.
class time
{ int h,m,s;
public: time()
{ h=0, m=0; s=0
} void getTime();
void show()
{ cout<< h<< ":"<< m<< ":"<< s;
} time operator+(time); //overloading '+' operator };
University Institute of Engineering
Overloading Relational operator

• You can also overload Relational operator like == , != , >= , <= etc. to compare two user-
defined object.
Example
class time
{ int hr,min,sec;
public: time()
{ hr=0, min=0; sec=0;
}
time(int h,int m, int s)
{ hr=h, min=m; sec=s;
}
friend bool operator==(time &t1, time &t2); //overloading '==' operator }; bool
operator== (time &t1, time &t2) //operator function
{ return ( t1.hr == t2.hr && t1.min == t2.min && t1.sec == t2.sec );
}

University Institute of Engineering


Unary Operators Overloading

• The unary operators operate on a single operand and


following are the examples of Unary operators −The
increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were
called and normally, this operator appears on the left side of
the object, as in !obj, -obj, and ++obj but sometime they can
be used as postfix as well like obj++ or obj--.

University Institute of Engineering


Constructor Overloading in C++

• In C++, We can have more than one constructor in a class


with same name, as long as each has a different list of
arguments.
• This concept is known as Constructor Overloading and is
quite similar to function overloading.
• Overloaded constructors essentially have the same name
(name of the class) and different number of arguments.
• A constructor is called depending upon the number and type
of arguments passed.
• While creating the object, arguments must be passed to let
compiler know, which constructor needs to be called.
University Institute of Engineering
References
• https://www.slideshare.net/gauravsitu/polymorphism-12270448
• https://www.slideshare.net/tareq1988/08-c-operator-
overloadingppt
• https://www.slideshare.net/AabhaTiwari1/operator-overloading-
in-c-59984971
• https://www.cis.upenn.edu/~matuszek/cit591-2012/Lectures/03-
polymorphism.ppt

University Institute of Engineering


Course Outcomes

•Identify the strengths of polymorphism in object oriented


programming.
• To gain the knowledge about function and operator
overloading.

University Institute of Engineering

You might also like