SlideShare a Scribd company logo
UNIT-5
POLYMORPHISM AND TYPE
CONVERSION
FACULTY NAME: Er. Kamaldeep Kaur
CHAPTER CONTENTS
 INTRODUCTION
 CONCEPT OF BINDING –EARLY BINDING AND LATE BINDING
 VIRTUAL FUNCTIONS
 PURE VIRTUAL FUNCTIONS
 OPERATOR OVERLOADING, RULES FOR OVERLOADING
OPERATORS, OVERLOADING OF VARIOUS OPERATORS,
 FUNCTION OVERLOADING, CONSTRUCTOR OVERLOADING,
 TYPE CONVERSION –BASIC TYPE TO CLASS TYPE, CLASS
TYPE TO BASIC TYPE, CLASS TYPE TO ANOTHER CLASS TYPE.
INTRODUCTION
 Polymorphism is derived from 2 Greek words: poly
and morphs.
 The word "poly" means many and morphs means
forms.
 So polymorphism means many forms.
REAL LIFE EXAMPLE OF POLYMORPHISM
 Suppose if you are in class room that time you
behave like a student, when you are in market at
that time you behave like a customer, when you at
your home at that time you behave like a son or
daughter, Here one person have different-different
behaviors.
TYPES OF POLYMORPHISM
TYPES OF POLYMORPHISM
 Polymorphism can be static or dynamic
 In static polymorphism memory will be allocated at compile-
time
 In dynamic polymorphism memory will be allocated at run-
time
 Both function overloading and operator overloading are an
examples of static polymorphism.
 Virtual function is an example of dynamic polymorphism.
 Static polymorphism is also known as early binding and
compile-time polymorphism.
 Dynamic polymorphism is also known as late binding and
run-time polymorphism.
STATIC POLYMORPHISM
 Also known as compile time polymorphism and early binding
 Binding means connecting function calls to appropriate
definition
 In this method object is bound to the function call at the compile
time itself
 It is implemented using function overloading and operator
overloading
 In function overloading, the member functions are selected for
invoking by matching arguments, both type and number. This
information is known to the compiler at compile time, and,
therefore, the compiler is able to select the appropriate
function for a particular call at the compile time itself.
FUNCTION OVERLOADING
OPERATOR OVERLOADING
 C++ tries to make the user-defined data types
behave in much the same way as the built-in types.
 For example, C++ permits to add two variables of
user defined data types, in a similar way as built-in
data type variables.
 So, operators can also be provided with a special
meaning for user defined data types.
 This mechanism of giving special meanings to
operators is known as Operator Overloading.
 When an operator is overloaded, its original
meaning is not lost.
EXCEPTIONS TO OVERLOADING
 All the operators in C++ can be overloaded except
the following:
 class member access operators (.)
 Pointer to member operator (.*)
 Scope resolution operator (::)
 Size operator (sizeof)
 Conditional operator (?:)
DEFINING OPERATOR OVERLOADING
 To define an additional task to an operator, must
specify its meaning in relation to the class to which
the operator is applied.
 This is done with the help of a special function,
called the operator function.
 Operator overloading can be with unary operators
and binary operators, known as UNARY OPERATOR
OVERLOADING and BINARY OPERATOR
OVERLOADING, respectively.
SYNTAX
 DECLARATION
 return_type operator op(arglist);
 DEFINITION
 return_type classname::operator op(arglist)
{ function body }
 Where return_type is the type of value returned by
the specified operation and op is the operator being
overloaded.
 The op is preceded by the keyword operator.
 operator is the function name.
OPERATOR FUNCTIONS
 The operator function can be either member function or friend
function.
 The object used to invoke the member function is passed
implicitly and therefore is available for the member function.
This is not the case with friend function.
DEFINING NUMBER OF ARGUMENTS
MEMBER FUNCTION FRIEND FUNCTION
UNARY OPERATOR
OVERLOADING
0 1
BINARY OPERATOR
OVERLOADING
1 2
PROCESS OF OVERLOADING
 THE PROCESS OF OVERLOADING INVOLVES THE
FOLLOWING STEPS:
 Create a class that defines the data type that is to
be used in the overloading operation.
 Declare the operator function operator op() in the
public part of the class.
 It may be either a member function or a friend
function.
 Define the operator function to implement the
required operations.
UNARY OPERATOR OVERLOADING
UNARY MINUS OPERATOR USING MEMBER FUNCTION
 #include <iostream>
using namespace std;
class space
{ int x;
public: void getdata(int a);
void display();
void operator -(); //can take int also
};
void space::getdata(int a)
{ x=a;}
void space::display()
{ cout<<"n"<<x;}
void space::operator-()
{ x=-x;}
 int main()
{ space s;
s.getdata(100);
s.display();
-s;
s.display();
return 0;
}
UNARY MINUS OPERATOR USING FRIEND
FUNCTION
 #include <iostream>
using namespace std;
class space
{ int x;
public:
void getdata(int a);
void display();
friend void operator -(space &s);
};
void space::getdata(int a)
{ x=a;}
void space::display()
{ cout<<"n"<<x;}
void operator-(space &s)
{ s.x=-s.x;}
 int main()
{
space s;
s.getdata(100);
s.display();
-s;
s.display();
return 0;
}
PREFIX INCREMENT OPERATOR
USING MEMBER FUNCTION
 #include <iostream>
using namespace std;
class check
{ int i;
public:
check() {i=0;}
void display() { cout<<"ni="<<i;}
void operator ++() {++i;} //return type can be any(int,classname,void),
//neednot write return statement
};
int main()
{ check obj;
obj.display();
++obj;
obj.display();
return 0;
}
POSTFIX INCREMENT OPERATOR
USING MEMBER FUNCTION
 #include <iostream>
using namespace std;
class check
{ int i;
public:
check() {i=0;}
void display() { cout<<"ni="<<i;}
void operator ++(int) {i++;}
};
int main()
{ check obj;
obj.display();
obj++;
obj.display();
return 0;
}
PREFIX INCREMENT OPERATOR
USING FRIEND FUNCTION
 #include <iostream>
using namespace std;
class check
{ int i;
public:
check() {i=0;}
void display() { cout<<"ni="<<i;}
friend void operator ++(check &obj) {++obj.i;}
};
int main()
{ check obj;
obj.display();
++obj;
obj.display();
return 0;
}
POSTFIX INCREMENT OPERATOR
USING FRIEND FUNCTION
 #include <iostream>
using namespace std;
class check
{ int i;
public:
check() {i=0;}
void display() { cout<<"ni="<<i;}
friend check operator ++(check &obj,int x) {obj.i++;}
};
int main()
{ check obj;
obj.display();
obj++;
obj.display();
return 0;
}
PREFIX & POSTFIX INCREMENT OPERATOR
USING MEMBER FUNCTION
 #include <iostream>
using namespace std;
class check
{ int i;
public:
check() {i=0;}
void display() { cout<<"ni="<<i;}
void operator ++() {++i;}
void operator ++(int) {i++;}
};
int main()
{ check obj;
obj.display();
++obj;
obj.display();
obj++;
obj.display();
return 0;
}
PREFIX & POSTFIX INCREMENT OPERATOR
USING FRIEND FUNCTION
 #include <iostream>
using namespace std;
class check
{ int i;
public:
check() {i=0;}
void display() { cout<<"ni="<<i;}
friend int operator ++(check &obj) {++obj.i;}
friend int operator ++(check &obj,int) {obj.i++;}
};
int main()
{ check obj;
obj.display();
++obj;
obj.display();
obj++;
obj.display();
return 0;
}
BINARY OPERATOR OVERLOADING
ARITHMETIC OPERATOR USING MEMBER FUNCTION
 #include <iostream>
using namespace std; int x; int y; int z; z=x+y;
class number
{ int x;
public:
void getdata(int a) { x=a;}
void show() {cout<<"nx="<<x;}
number operator +(number n2) //class as the return type
{ number n4;
n4.x=x+n2.x;
}
};
int main()
{ number n1,n2;
n1.getdata(10); //n1.x=10
n2.getdata(20); //n2.x=20
number n3;
n3=n1+n2; // or n3=n1.operator+(n2); //first variable is implicitly passed, second
n3.show(); //variable is explicitly passed
}
ARITHMETIC OPERATOR USING FRIEND
FUNCTION
 #include <iostream>
using namespace std;
class number
{ int x;
public:
void getdata(int a) { x=a;}
void show() {cout<<"nx="<<x;}
friend number operator +(number n1,number n2)
{ number n4;
n4.x=n1.x+n2.x;
}
};
int main()
{ number n1,n2;
n1.getdata(10);
n2.getdata(20);
number n3;
n3=n1+n2; // or n3=operator+(n1,n2);
n3.show();
}
RELATIONAL OPERATOR USING MEMBER
FUNCTION
 #include <iostream>
using namespace std;
class number
{ int x;
public:
number(int a) {x=a;}
void display() { cout<<"nx="<<x;}
int operator <(number n) {return (x<n.x);}
};
int main()
{ number i(23),j(24);
cout<<"smaller number";
if(i<j)
i.display();
else
j.display();
return 0;
}
PROGRAM TO ADD TWO COMPLEX NUMBERS
USING BINARY OPERATOR OVERLOADING
 #include<iostream>
using namespace std;
class complex
{float x,y;
public: complex(){}
complex(float real, float imag)
{x=real; y=imag;}
friend complex operator+(complex,complex);
void display()
{cout<<"nthe sum is"<<x<<"+i"<<y;}};
complex operator+(complex t1,complex t2)
{ complex temp;
temp.x=t1.x+t2.x;
temp.y=t1.y+t2.y;
return(temp);
}
int main()
{complex t1(2.5,3.5);
complex t2(1.6,2.7);
complex t3;
t3=t1+t2;
t1.display();
t2.display();
t3.display();
return(0);}
WHERE A FRIEND FUNCTION CANNOT BE USED
 Assignment operator =
 Function call operator ()
 Subscripting operator []
 Class member access operator 
DYNAMIC POLYMORPHISM
 The appropriate member function is selected when
the program is running.
 C++ supports virtual functions to achieve run time
polymorphism.
 At run time, when it is known what class objects are
under consideration, the appropriate version of the
function is invoked.
 It requires the use of pointers to objects.
POINTERS TO OBJECTS
Object Pointers are used to create objects at run time.
class item
{
int code;
float price;
public:
void getdata(int a, float b)
{
code=a;
price=b;
}
void show()
{
cout<<“code=“<<code;
cout<<“price=“<<price;
}};
int main()
{
item x;
item *p=&x;
x.getdata(100,75.50);
x.show();
pgetdata(100,75.50);
pshow();
(*p).show();
(*p).getdata(100,75.50);
}
FUNCTION OVERRIDING
 It is the redefinition of base class function in its
derived class with same signature i.e return type
and parameters.
 It can only be done in derived class.
FUNCTION OVERRIDING
class A
{ public:
void display()
{
cout<<“nA”;
}
};
class B: public A//syntax for inheritance
{ public:
void display()
{
cout<<“nB”;
}
};
int main()
{
B b;
b.display(); //overriding
b.A::display();
b.B::display();
}
OUTPUT:
B
A
B
VIRTUAL FUNCTIONS
 A virtual function is a member function which is declared within
a base class and is re-defined (overriden) by a derived class.
 When refer to a derived class object using a pointer or a
reference to the base class, can call a virtual function for that
object and execute the derived class’s version of the function.
 Virtual functions ensure that the correct function is called for an
object, regardless of the type of reference (or pointer) used
for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at Run-time.
VIRTUAL FUNCTIONS
 So, when a function is made virtual, C++
determines which function to use at run time based
on the type of object pointed to by the base
pointer, rather than the type of pointer.
 If not making function virtual, then the base pointer
will call only the base class function in both cases.
VIRTUAL FUNCTIONS
 #include <iostream>
using namespace std;
class base {
public:
virtual void print()
{ cout << "print base class" << endl;
}
void show()
{ cout << "show base class" << endl;
}
};
class derived : public base {
public:
void print()
{ cout << "print derived class" << endl; }
void show()
{ cout << "show derived class" << endl; }
};
int main()
{
base* bptr;
derived d;
bptr = &d;
// virtual function, binded at runtime
bptrprint();
// Non-virtual function, binded at compile
time
bptrshow();
}
 OUTPUT:
print derived class
show base class
PURE VIRTUAL FUNCTIONS
 A pure virtual function (or abstract function) in C++ is a virtual
function for which we don’t have implementation, we only
declare it.
 A pure virtual function is declared by assigning 0 in
declaration.
 EXAMPLE:
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;
/* Other members */
};
PURE VIRTUAL FUNCTIONS
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
// This class inherits from Base,implements fun()
class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called";
}
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
OUTPUT:
fun() called
ABSTRACT CLASS
 A class is abstract if it has at least one pure virtual
function.
 Can’t declare objects of an abstract class.
 can have pointers and references of abstract class
type.
 If do not override the pure virtual function in derived
class, then derived class also becomes abstract class.
TYPE CONVERSION
 The type conversions in C++ are automatic as long
as the data types involved are built in types.
 That is, the automatic type conversion is only for
basic data types, not for user defined data types.
 Need to design conversion routines for various data
types.
 Three types of conversions are possible for user
defined data
 Conversion from basic type to class type
 Conversion from class type to basic type
 Conversion from one class type to another class type
TYPE CONVERSION
SOURCE TO DESTINATION SOURCE CLASS DESTINATION CLASS
Basic to class Not applicable Constructor
Class to basic Casting operator Not applicable
Class to class Casting operator Constructor
CONVERSION FROM BASIC TO CLASS TYPE
 In this type of conversion the source type is basic type and the
destination type is class type. Means basic data type is
converted into the class type.
 This is done with the help of constructor.
 The constructor used for this type conversion takes a single
argument whose type is to be converted.
 It is automatically done by the compiler with the help of built in
routines.
 The left hand operand of = sign is always class type and right
hand operand is always basic type.
BASIC TO CLASS TYPE
class data
{ int x; float f; OUTPUT:
public: 0 0
data() 2 1
{x=0; f=0;} 2 2.5
data(float m)
{x=2; f=m;}
void show()
{cout<<x<<"t"<<f<<"n";}
};
main()
{ data z;
z.show();
z=1;
z.show();
z=2.5;
z.show();
}
BASIC TO CLASS TYPE
class time
{ int hrs;
int min;
public:
time(int t)
{ hrs=t/60;
min=t%60;
}};
main()
{
time T;
int duration=85;
T=duration;
}
//after execution, hrs will contain value 1 and min a value of 25, denoting 1 hr 25
minutes.
CLASS TO BASIC TYPE
 The constructor function doesnot support this
operation.
 C++ defines an additional casting operator that
could be used to convert class type to basic type.
 operator typename(){ }
 The casting operator must be a class member, must
not specify a return type and must not have any
arguments.
 In this, the left hand operand is always of basic data
type and right hand operand is of class data type.
CLASS TO BASIC TYPE
class data
{
int x;
float f;
public:
data()
{x=0; y=0;}
data(int p,float q)
{x=p;f=q;}
operator int()
{
return x;
}
operator float()
{
return f;
}
};
int main()
{
int j;
float f;
data a(0,5.5);
j=a; //operator int
f=a;//operator float
cout<<j<<“t”<<f<<“n”;
}
OUTPUT:
0 5.5
CLASS TO CLASS TYPE
 Can convert one class type to another class type as
follows:
 Object of A= Object of B;
 //from class B to class A, B- source class, A-destination class
 Class type to another class type can be converted by the
following ways:
1. BY CONSTRUCTOR: When the conversion routine is in
destination class, it is implemented as a constructor.
2. BY CONVERSION FUNCTION: When the conversion routine is
in source class, it is implemented as a conversion function.
CLASS TO CLASS TYPE (WITH CONSTRUCTOR)
#include<math>
#include<iostream>
class polar
{ float rd; float ang;
public: polar()
{rd=0.0; ang=0.0;}
polar(float r, float a)
{rd=r; ang=a;}
float getrd()
{ return rd;}
float getang()
{ return ang;}
void showpolar()
{ cout<<rd<<ang<<endl;}};
class rec
{ float x;
float y;
public: rec() {x=0.0; y=0.0;}
rec(float xco,float yco)
{x=xco; y=yco;}
rec(polar p)
{ float r=p.getrd();
float a=p.getang();
x=r*cos(a);
y=r*sin(a); }
void showrec()
{cout<<x<<y<<endl;}
main()
{ rec r1;
polar p1(2.0,90.0);
r1=p1;
cout<<“polar coordinates”;
p1.showpolar();
cout<<“rec coordinates”;
r1.showpolar(); }
CLASS TO CLASS TYPE (WITH CONVERSION
FUNCTION)
#include<math>
#include<iostream>
class rec
{ float x; float y;
public: rec()
{ x=0.0; y=0.0;}
rec(float xco, float yco)
{ x=xco; y=yco;}
void showrec()
{ cout<<x<<y<<endl;}};
class polar
{ float rd; float ang;
public: polar(){rd=0.0; ang=0.0;}
polar(float r, float a)
{ rd=r; ang=a;}
operator rec()
{ float x1=rd*cos(ang);
float y1=rd*sin(ang);
return rec(x1,y1);}
void showpolar()
{cout<<rd<<ang<<endl;}
int main()
{ rec r1;
polar p1(2.0,90.0);
r1=p1;
cout<<“polar coordinates”;
p1.showpolar();
cout<<“rec coordinates”;
r1.showrec();
}

More Related Content

Similar to Polymorphism and Type Conversion.pdf pot (20)

PDF
Unit3_OOP-converted.pdf
PowerfullBoy1
 
PPT
Operator Overloading
Nilesh Dalvi
 
PPT
14 operator overloading
Docent Education
 
PPTX
Operator overloaing
zindadili
 
PPT
Overloading
Mukhtar_Hunzai
 
PPTX
Operator overloading
ramya marichamy
 
PPTX
Oops
ankush_kumar
 
PDF
Lec 8.pdf a
aliashraf9689
 
PPTX
Operator overloading2
zindadili
 
PDF
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
PPTX
Operator overloading
Kumar
 
PPT
Operator overloading
ArunaDevi63
 
PPTX
Operator overloading
Garima Singh Makhija
 
PPT
3d7b7 session4 c++
Mukund Trivedi
 
PPTX
Operator Overloading
Juginder Pal Singh
 
PDF
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PPT
Lec 26.27-operator overloading
Princess Sam
 
PPTX
B.sc CSIT 2nd semester C++ Unit4
Tekendra Nath Yogi
 
PPTX
Operator overloading and type conversion in cpp
rajshreemuthiah
 
PPT
Lec 28 - operator overloading
Princess Sam
 
Unit3_OOP-converted.pdf
PowerfullBoy1
 
Operator Overloading
Nilesh Dalvi
 
14 operator overloading
Docent Education
 
Operator overloaing
zindadili
 
Overloading
Mukhtar_Hunzai
 
Operator overloading
ramya marichamy
 
Lec 8.pdf a
aliashraf9689
 
Operator overloading2
zindadili
 
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
Operator overloading
Kumar
 
Operator overloading
ArunaDevi63
 
Operator overloading
Garima Singh Makhija
 
3d7b7 session4 c++
Mukund Trivedi
 
Operator Overloading
Juginder Pal Singh
 
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Lec 26.27-operator overloading
Princess Sam
 
B.sc CSIT 2nd semester C++ Unit4
Tekendra Nath Yogi
 
Operator overloading and type conversion in cpp
rajshreemuthiah
 
Lec 28 - operator overloading
Princess Sam
 

Recently uploaded (20)

PPTX
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PDF
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PDF
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
PDF
Tips for Writing the Research Title with Examples
Thelma Villaflores
 
PPTX
Applied-Statistics-1.pptx hardiba zalaaa
hardizala899
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
PPTX
LDP-2 UNIT 4 Presentation for practical.pptx
abhaypanchal2525
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
Virus sequence retrieval from NCBI database
yamunaK13
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Basics and rules of probability with real-life uses
ravatkaran694
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
Tips for Writing the Research Title with Examples
Thelma Villaflores
 
Applied-Statistics-1.pptx hardiba zalaaa
hardizala899
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
LDP-2 UNIT 4 Presentation for practical.pptx
abhaypanchal2525
 
Ad

Polymorphism and Type Conversion.pdf pot

  • 2. CHAPTER CONTENTS  INTRODUCTION  CONCEPT OF BINDING –EARLY BINDING AND LATE BINDING  VIRTUAL FUNCTIONS  PURE VIRTUAL FUNCTIONS  OPERATOR OVERLOADING, RULES FOR OVERLOADING OPERATORS, OVERLOADING OF VARIOUS OPERATORS,  FUNCTION OVERLOADING, CONSTRUCTOR OVERLOADING,  TYPE CONVERSION –BASIC TYPE TO CLASS TYPE, CLASS TYPE TO BASIC TYPE, CLASS TYPE TO ANOTHER CLASS TYPE.
  • 3. INTRODUCTION  Polymorphism is derived from 2 Greek words: poly and morphs.  The word "poly" means many and morphs means forms.  So polymorphism means many forms.
  • 4. REAL LIFE EXAMPLE OF POLYMORPHISM  Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person have different-different behaviors.
  • 6. TYPES OF POLYMORPHISM  Polymorphism can be static or dynamic  In static polymorphism memory will be allocated at compile- time  In dynamic polymorphism memory will be allocated at run- time  Both function overloading and operator overloading are an examples of static polymorphism.  Virtual function is an example of dynamic polymorphism.  Static polymorphism is also known as early binding and compile-time polymorphism.  Dynamic polymorphism is also known as late binding and run-time polymorphism.
  • 7. STATIC POLYMORPHISM  Also known as compile time polymorphism and early binding  Binding means connecting function calls to appropriate definition  In this method object is bound to the function call at the compile time itself  It is implemented using function overloading and operator overloading  In function overloading, the member functions are selected for invoking by matching arguments, both type and number. This information is known to the compiler at compile time, and, therefore, the compiler is able to select the appropriate function for a particular call at the compile time itself.
  • 9. OPERATOR OVERLOADING  C++ tries to make the user-defined data types behave in much the same way as the built-in types.  For example, C++ permits to add two variables of user defined data types, in a similar way as built-in data type variables.  So, operators can also be provided with a special meaning for user defined data types.  This mechanism of giving special meanings to operators is known as Operator Overloading.  When an operator is overloaded, its original meaning is not lost.
  • 10. EXCEPTIONS TO OVERLOADING  All the operators in C++ can be overloaded except the following:  class member access operators (.)  Pointer to member operator (.*)  Scope resolution operator (::)  Size operator (sizeof)  Conditional operator (?:)
  • 11. DEFINING OPERATOR OVERLOADING  To define an additional task to an operator, must specify its meaning in relation to the class to which the operator is applied.  This is done with the help of a special function, called the operator function.  Operator overloading can be with unary operators and binary operators, known as UNARY OPERATOR OVERLOADING and BINARY OPERATOR OVERLOADING, respectively.
  • 12. SYNTAX  DECLARATION  return_type operator op(arglist);  DEFINITION  return_type classname::operator op(arglist) { function body }  Where return_type is the type of value returned by the specified operation and op is the operator being overloaded.  The op is preceded by the keyword operator.  operator is the function name.
  • 13. OPERATOR FUNCTIONS  The operator function can be either member function or friend function.  The object used to invoke the member function is passed implicitly and therefore is available for the member function. This is not the case with friend function. DEFINING NUMBER OF ARGUMENTS MEMBER FUNCTION FRIEND FUNCTION UNARY OPERATOR OVERLOADING 0 1 BINARY OPERATOR OVERLOADING 1 2
  • 14. PROCESS OF OVERLOADING  THE PROCESS OF OVERLOADING INVOLVES THE FOLLOWING STEPS:  Create a class that defines the data type that is to be used in the overloading operation.  Declare the operator function operator op() in the public part of the class.  It may be either a member function or a friend function.  Define the operator function to implement the required operations.
  • 15. UNARY OPERATOR OVERLOADING UNARY MINUS OPERATOR USING MEMBER FUNCTION  #include <iostream> using namespace std; class space { int x; public: void getdata(int a); void display(); void operator -(); //can take int also }; void space::getdata(int a) { x=a;} void space::display() { cout<<"n"<<x;} void space::operator-() { x=-x;}  int main() { space s; s.getdata(100); s.display(); -s; s.display(); return 0; }
  • 16. UNARY MINUS OPERATOR USING FRIEND FUNCTION  #include <iostream> using namespace std; class space { int x; public: void getdata(int a); void display(); friend void operator -(space &s); }; void space::getdata(int a) { x=a;} void space::display() { cout<<"n"<<x;} void operator-(space &s) { s.x=-s.x;}  int main() { space s; s.getdata(100); s.display(); -s; s.display(); return 0; }
  • 17. PREFIX INCREMENT OPERATOR USING MEMBER FUNCTION  #include <iostream> using namespace std; class check { int i; public: check() {i=0;} void display() { cout<<"ni="<<i;} void operator ++() {++i;} //return type can be any(int,classname,void), //neednot write return statement }; int main() { check obj; obj.display(); ++obj; obj.display(); return 0; }
  • 18. POSTFIX INCREMENT OPERATOR USING MEMBER FUNCTION  #include <iostream> using namespace std; class check { int i; public: check() {i=0;} void display() { cout<<"ni="<<i;} void operator ++(int) {i++;} }; int main() { check obj; obj.display(); obj++; obj.display(); return 0; }
  • 19. PREFIX INCREMENT OPERATOR USING FRIEND FUNCTION  #include <iostream> using namespace std; class check { int i; public: check() {i=0;} void display() { cout<<"ni="<<i;} friend void operator ++(check &obj) {++obj.i;} }; int main() { check obj; obj.display(); ++obj; obj.display(); return 0; }
  • 20. POSTFIX INCREMENT OPERATOR USING FRIEND FUNCTION  #include <iostream> using namespace std; class check { int i; public: check() {i=0;} void display() { cout<<"ni="<<i;} friend check operator ++(check &obj,int x) {obj.i++;} }; int main() { check obj; obj.display(); obj++; obj.display(); return 0; }
  • 21. PREFIX & POSTFIX INCREMENT OPERATOR USING MEMBER FUNCTION  #include <iostream> using namespace std; class check { int i; public: check() {i=0;} void display() { cout<<"ni="<<i;} void operator ++() {++i;} void operator ++(int) {i++;} }; int main() { check obj; obj.display(); ++obj; obj.display(); obj++; obj.display(); return 0; }
  • 22. PREFIX & POSTFIX INCREMENT OPERATOR USING FRIEND FUNCTION  #include <iostream> using namespace std; class check { int i; public: check() {i=0;} void display() { cout<<"ni="<<i;} friend int operator ++(check &obj) {++obj.i;} friend int operator ++(check &obj,int) {obj.i++;} }; int main() { check obj; obj.display(); ++obj; obj.display(); obj++; obj.display(); return 0; }
  • 23. BINARY OPERATOR OVERLOADING ARITHMETIC OPERATOR USING MEMBER FUNCTION  #include <iostream> using namespace std; int x; int y; int z; z=x+y; class number { int x; public: void getdata(int a) { x=a;} void show() {cout<<"nx="<<x;} number operator +(number n2) //class as the return type { number n4; n4.x=x+n2.x; } }; int main() { number n1,n2; n1.getdata(10); //n1.x=10 n2.getdata(20); //n2.x=20 number n3; n3=n1+n2; // or n3=n1.operator+(n2); //first variable is implicitly passed, second n3.show(); //variable is explicitly passed }
  • 24. ARITHMETIC OPERATOR USING FRIEND FUNCTION  #include <iostream> using namespace std; class number { int x; public: void getdata(int a) { x=a;} void show() {cout<<"nx="<<x;} friend number operator +(number n1,number n2) { number n4; n4.x=n1.x+n2.x; } }; int main() { number n1,n2; n1.getdata(10); n2.getdata(20); number n3; n3=n1+n2; // or n3=operator+(n1,n2); n3.show(); }
  • 25. RELATIONAL OPERATOR USING MEMBER FUNCTION  #include <iostream> using namespace std; class number { int x; public: number(int a) {x=a;} void display() { cout<<"nx="<<x;} int operator <(number n) {return (x<n.x);} }; int main() { number i(23),j(24); cout<<"smaller number"; if(i<j) i.display(); else j.display(); return 0; }
  • 26. PROGRAM TO ADD TWO COMPLEX NUMBERS USING BINARY OPERATOR OVERLOADING  #include<iostream> using namespace std; class complex {float x,y; public: complex(){} complex(float real, float imag) {x=real; y=imag;} friend complex operator+(complex,complex); void display() {cout<<"nthe sum is"<<x<<"+i"<<y;}}; complex operator+(complex t1,complex t2) { complex temp; temp.x=t1.x+t2.x; temp.y=t1.y+t2.y; return(temp); } int main() {complex t1(2.5,3.5); complex t2(1.6,2.7); complex t3; t3=t1+t2; t1.display(); t2.display(); t3.display(); return(0);}
  • 27. WHERE A FRIEND FUNCTION CANNOT BE USED  Assignment operator =  Function call operator ()  Subscripting operator []  Class member access operator 
  • 28. DYNAMIC POLYMORPHISM  The appropriate member function is selected when the program is running.  C++ supports virtual functions to achieve run time polymorphism.  At run time, when it is known what class objects are under consideration, the appropriate version of the function is invoked.  It requires the use of pointers to objects.
  • 29. POINTERS TO OBJECTS Object Pointers are used to create objects at run time. class item { int code; float price; public: void getdata(int a, float b) { code=a; price=b; } void show() { cout<<“code=“<<code; cout<<“price=“<<price; }}; int main() { item x; item *p=&x; x.getdata(100,75.50); x.show(); pgetdata(100,75.50); pshow(); (*p).show(); (*p).getdata(100,75.50); }
  • 30. FUNCTION OVERRIDING  It is the redefinition of base class function in its derived class with same signature i.e return type and parameters.  It can only be done in derived class.
  • 31. FUNCTION OVERRIDING class A { public: void display() { cout<<“nA”; } }; class B: public A//syntax for inheritance { public: void display() { cout<<“nB”; } }; int main() { B b; b.display(); //overriding b.A::display(); b.B::display(); } OUTPUT: B A B
  • 32. VIRTUAL FUNCTIONS  A virtual function is a member function which is declared within a base class and is re-defined (overriden) by a derived class.  When refer to a derived class object using a pointer or a reference to the base class, can call a virtual function for that object and execute the derived class’s version of the function.  Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.  They are mainly used to achieve Runtime polymorphism  Functions are declared with a virtual keyword in base class.  The resolving of function call is done at Run-time.
  • 33. VIRTUAL FUNCTIONS  So, when a function is made virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer, rather than the type of pointer.  If not making function virtual, then the base pointer will call only the base class function in both cases.
  • 34. VIRTUAL FUNCTIONS  #include <iostream> using namespace std; class base { public: virtual void print() { cout << "print base class" << endl; } void show() { cout << "show base class" << endl; } }; class derived : public base { public: void print() { cout << "print derived class" << endl; } void show() { cout << "show derived class" << endl; } }; int main() { base* bptr; derived d; bptr = &d; // virtual function, binded at runtime bptrprint(); // Non-virtual function, binded at compile time bptrshow(); }  OUTPUT: print derived class show base class
  • 35. PURE VIRTUAL FUNCTIONS  A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it.  A pure virtual function is declared by assigning 0 in declaration.  EXAMPLE: class Test { // Data members of class public: // Pure Virtual Function virtual void show() = 0; /* Other members */ };
  • 36. PURE VIRTUAL FUNCTIONS #include<iostream> using namespace std; class Base { int x; public: virtual void fun() = 0; int getX() { return x; } }; // This class inherits from Base,implements fun() class Derived: public Base { int y; public: void fun() { cout << "fun() called"; } }; int main(void) { Derived d; d.fun(); return 0; } OUTPUT: fun() called
  • 37. ABSTRACT CLASS  A class is abstract if it has at least one pure virtual function.  Can’t declare objects of an abstract class.  can have pointers and references of abstract class type.  If do not override the pure virtual function in derived class, then derived class also becomes abstract class.
  • 38. TYPE CONVERSION  The type conversions in C++ are automatic as long as the data types involved are built in types.  That is, the automatic type conversion is only for basic data types, not for user defined data types.  Need to design conversion routines for various data types.  Three types of conversions are possible for user defined data  Conversion from basic type to class type  Conversion from class type to basic type  Conversion from one class type to another class type
  • 39. TYPE CONVERSION SOURCE TO DESTINATION SOURCE CLASS DESTINATION CLASS Basic to class Not applicable Constructor Class to basic Casting operator Not applicable Class to class Casting operator Constructor
  • 40. CONVERSION FROM BASIC TO CLASS TYPE  In this type of conversion the source type is basic type and the destination type is class type. Means basic data type is converted into the class type.  This is done with the help of constructor.  The constructor used for this type conversion takes a single argument whose type is to be converted.  It is automatically done by the compiler with the help of built in routines.  The left hand operand of = sign is always class type and right hand operand is always basic type.
  • 41. BASIC TO CLASS TYPE class data { int x; float f; OUTPUT: public: 0 0 data() 2 1 {x=0; f=0;} 2 2.5 data(float m) {x=2; f=m;} void show() {cout<<x<<"t"<<f<<"n";} }; main() { data z; z.show(); z=1; z.show(); z=2.5; z.show(); }
  • 42. BASIC TO CLASS TYPE class time { int hrs; int min; public: time(int t) { hrs=t/60; min=t%60; }}; main() { time T; int duration=85; T=duration; } //after execution, hrs will contain value 1 and min a value of 25, denoting 1 hr 25 minutes.
  • 43. CLASS TO BASIC TYPE  The constructor function doesnot support this operation.  C++ defines an additional casting operator that could be used to convert class type to basic type.  operator typename(){ }  The casting operator must be a class member, must not specify a return type and must not have any arguments.  In this, the left hand operand is always of basic data type and right hand operand is of class data type.
  • 44. CLASS TO BASIC TYPE class data { int x; float f; public: data() {x=0; y=0;} data(int p,float q) {x=p;f=q;} operator int() { return x; } operator float() { return f; } }; int main() { int j; float f; data a(0,5.5); j=a; //operator int f=a;//operator float cout<<j<<“t”<<f<<“n”; } OUTPUT: 0 5.5
  • 45. CLASS TO CLASS TYPE  Can convert one class type to another class type as follows:  Object of A= Object of B;  //from class B to class A, B- source class, A-destination class  Class type to another class type can be converted by the following ways: 1. BY CONSTRUCTOR: When the conversion routine is in destination class, it is implemented as a constructor. 2. BY CONVERSION FUNCTION: When the conversion routine is in source class, it is implemented as a conversion function.
  • 46. CLASS TO CLASS TYPE (WITH CONSTRUCTOR) #include<math> #include<iostream> class polar { float rd; float ang; public: polar() {rd=0.0; ang=0.0;} polar(float r, float a) {rd=r; ang=a;} float getrd() { return rd;} float getang() { return ang;} void showpolar() { cout<<rd<<ang<<endl;}}; class rec { float x; float y; public: rec() {x=0.0; y=0.0;} rec(float xco,float yco) {x=xco; y=yco;} rec(polar p) { float r=p.getrd(); float a=p.getang(); x=r*cos(a); y=r*sin(a); } void showrec() {cout<<x<<y<<endl;} main() { rec r1; polar p1(2.0,90.0); r1=p1; cout<<“polar coordinates”; p1.showpolar(); cout<<“rec coordinates”; r1.showpolar(); }
  • 47. CLASS TO CLASS TYPE (WITH CONVERSION FUNCTION) #include<math> #include<iostream> class rec { float x; float y; public: rec() { x=0.0; y=0.0;} rec(float xco, float yco) { x=xco; y=yco;} void showrec() { cout<<x<<y<<endl;}}; class polar { float rd; float ang; public: polar(){rd=0.0; ang=0.0;} polar(float r, float a) { rd=r; ang=a;} operator rec() { float x1=rd*cos(ang); float y1=rd*sin(ang); return rec(x1,y1);} void showpolar() {cout<<rd<<ang<<endl;} int main() { rec r1; polar p1(2.0,90.0); r1=p1; cout<<“polar coordinates”; p1.showpolar(); cout<<“rec coordinates”; r1.showrec(); }