Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

Topics Covered

Polymorphism : 43
 functions overloading,
 overloading unary operators,
 overloading binary operators,
 virtual base classes,
 abstract classes,
 pointer to object,
 this pointer,
 pointer to derived class,
 virtual function,
 pure virtual function

OBJECT ORIENTED PROGRAMMING USING C++


Polymorphism
Polymorphism uses those methods to perform
different tasks.
This allows us to perform a single action in
different ways.

OBJECT ORIENTED PROGRAMMING USING C++


• The term "Polymorphism" is the combination of "poly" + "morphs"
which means many forms.
• It is a greek word.
• In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation, and polymorphism.
• Real Life Example Of Polymorphism
• Let's consider a real-life example of polymorphism.
• A lady behaves like a teacher in a classroom, mother or daughter in a
home and customer in a market.
• Here, a single person is behaving differently according to the
situations.

OBJECT ORIENTED PROGRAMMING USING C++


OBJECT ORIENTED PROGRAMMING USING C++
• Compile time polymorphism:
• The overloaded functions are invoked by matching the type and
number of arguments.
• This information is available at the compile time and, therefore,
compiler selects the appropriate function at the compile time.
• It is achieved by function overloading and operator overloading
which is also known as static binding or early binding.
• Run time polymorphism:
• Run time polymorphism is achieved when the object's method is
invoked at the run time instead of compile time.
• It is achieved by method overriding which is also known as dynamic
binding or late binding.

OBJECT ORIENTED PROGRAMMING USING C++


• If we create two or more members having the same name but
different in number or type of parameter, it is known as C++
overloading.
• In C++, we can overload:
Methods
Constructors
Indexed properties
• It is because these members have parameters only.
• Types of overloading in C++ are:
• Function overloading
• Operator overloading

OBJECT ORIENTED PROGRAMMING USING C++


 Functions overloading

 same function name but different parameters.


 same function name with different signature
 example of polymorphism(compile time)
 overloaded functions should be there in same
class.
C++ Function Overloading
• Function Overloading is defined as the process of
having two or more function with the same name,
but different in parameters is known as function
overloading in C++

OBJECT ORIENTED PROGRAMMING USING C++


Advantage of Function overloading is that it
increases the readability of the program
because you don't need to use different names
for the same action.

Example

int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
OBJECT ORIENTED PROGRAMMING USING C++
• #include <iostream>
• using namespace std;

• int sum(int a,int b)


• {
• return a+b;
• }
• int sum(int a,int b ,int c )
• {
• return a+b+c;
• }
• double sum(double a,double b)
• {
• return a+b;
• }
• int main() {

• cout<<"sum of integer nos : "<<sum(10,20)<<endl;

• cout<<"sum of double nos : "<<sum(10.9,20.9)<<endl;
• cout<<"sum of 3 integer nos : "<<sum(1,2,3);
• }

OBJECT ORIENTED PROGRAMMING USING C++


Operator overloading

Operator overloading is a compile-time polymorphism


in which the operator is overloaded to provide the
special meaning to the user-defined data type.
Operator that cannot be overloaded are as follows:
• Scope operator (::)
• Size operator sizeof()
• Conditional operator ?
• member selector(.)

OBJECT ORIENTED PROGRAMMING USING C++


Operators which can overload

OBJECT ORIENTED PROGRAMMING USING C++


Consider this example
class A
{
};
int main()
{
A a1,a2,a3;
a3= a1 + a2;
return 0;
}
Error
because the addition operator “+” is predefined to operate
only on built-in data types

OBJECT ORIENTED PROGRAMMING USING C++


• Operator overloading is a compile-time
polymorphism. It is an idea of giving special
meaning to an existing operator in C++ without
changing its original meaning.
Example:
• int a;
float b,sum;
sum=a+b;
• variables “a” and “b” are of types “int” and “float”, which
are built-in data types. The addition operator ‘+’ can easily
add the contents of “a” and “b”.
• This is because the addition operator “+” is predefined to
add variables of built-in data type only.

OBJECT ORIENTED PROGRAMMING USING C++


Syntax
To overload an operator, we use a special operator function

class className
{ ... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};

OBJECT ORIENTED PROGRAMMING USING C++


Syntax 1:
Operator Overloading Syntax:
return_type operator operator_Symbol(parameters)
{

}
Syntax2 :
returntype classname : : operator operatortobeoverloaded
(argument_list)
{
// body of the function.
}

OBJECT ORIENTED PROGRAMMING USING C++


• Two types of operator overloading
• Unary: operates on single operand like ++, - -
• Unary operators operate on only one operand.
• The increment operator ++ and decrement operator -- are
examples of unary operators.
• Binary : Binary operators work on two operands
• Eg s=a+b;
• Here, + is a binary operator that works on the operands
num and 9.
• When we overload the binary operator for user-defined
types by using the code:
• obj3 = obj1 + obj2;

OBJECT ORIENTED PROGRAMMING USING C++


Operator overloading for Unary
operators:
The unary operators operate on a single
operand :
• The increment (++) and decrement (--)
operators.
• The unary minus (-) operator.
• The logical not (!) operator.

OBJECT ORIENTED PROGRAMMING USING C++


Operator overloading for binary operators:

The binary operators operate on two


operands :
+, a+b
-,
*,
/,
%

OBJECT ORIENTED PROGRAMMING USING C++


Syntax
To overload an operator, we use a special
operator function
class className
{ ... .. ...
public
returnType operator symbol (arguments) {
... .. ...
Created By:
} Kumar Vishal
(SCA), LPU
... .. ...
OBJECT ORIENTED PROGRAMMING USING C++
SYNTAX HOW TO CALL OPERATOR OVERLODAED FUNCTION

SYNTAX For Unary Opertor :

X operator or operator x // X.operator()

SYNTAX For Unary Opertor for friend function

operator(x)

SYNTAX For Binary Opertor :

X .operator( y ) or x+y

SYNTAX For Binary Opertor for friend function:

Operartor (x,y)

OBJECT ORIENTED PROGRAMMING USING C++


• // UNARY OPERATOR PROGRAM
• #include <iostream>
• using namespace std;

• class Unary {
• public:
• int value=9;
• // Overload ++ when used as prefix
• void operator ++ () {
• value++;
• }

• void display() {
• cout << "Count: " << value << endl;
• }
• };

• int main() {
• Unary count1;

• // Call the "void operator ++ ()" function


• ++count1; // count1.operator

• count1.display();
• return 0;
• }

OBJECT ORIENTED PROGRAMMING USING C++


• Example 2: ++ Operator (Unary Operator) Overloading
• #include <iostream>
• using namespace std;

• class Unary {
• public:
• int value=6;
• // Overload ++ when used as prefix
• void operator ++ () {
• ++value;
• }

• void display() {
• cout << "Count: " << value << endl;
• }
• };

• int main() {
• Unary count1;

• // Call the "void operator ++ ()" function


• ++count1;

• count1.display();
• return 0;
• }

• KUNDAN

OBJECT ORIENTED PROGRAMMING USING C++


• // PROGRAM UNARY OPERATOR

• #include <iostream>
• using namespace std;

• class Unary {
• public:
• int value=4;
• // Overload ++ when used as prefix
• void operator -- () {
• --value;
• }

• void display() {
• cout << "Count: " << value << endl;
• }
• };

• int main() {
• Unary count1;

• // Call the "void operator ++ ()" function


• --count1;

• count1.display();
• return 0;
• }

OBJECT ORIENTED PROGRAMMING USING C++


• //Write a program which will covert positive value to
negative
• #include<iostream>
• using namespace std;
• class lpu {
• int x, y;
• public:
• void getdata(int a, int b){
• x=a;
• y=b;
• }
• void display() {
• cout<<x<<endl;
• cout<<y<<endl;
• }
• void operator-();
• };

• void lpu::operator-(){
• x=-x;
• y=-y;
• };
• int main()
• {
• lpu obj;
• obj.getdata(10,-20);
• obj.display();
• -obj; //or obj.operator-();
• obj.display();
• }

OBJECT ORIENTED PROGRAMMING USING C++
• // BINARY OPERATOR OVERLOADING

• #include<iostream>
• using namespace std;
• class A
• {
• public:
• int x;
• A(int i)
• {
• x=i;
• }
• void operator+(A a)
• {
• int m = x+a.x; // a represents obj 2
• cout<<"The result of the addition of two objects is : "<<m;

• }

• };


• int main()
• {
• A a1(4);
• A a2(5);
• a1+a2; //a1.operator(a2)
• return 0;
• }

OBJECT ORIENTED PROGRAMMING USING C++


Rules for Operator Overloading
Existing operators can only be overloaded.
The overloaded operator contains at least one
operand of the user-defined data type.
When unary operators are overloaded through a
member function take no explicit arguments, but,
if they are overloaded by a friend function, takes
one argument.
When binary operators are overloaded through a
member function takes one explicit argument,
and if they are overloaded through a friend
function takes two explicit arguments.

OBJECT ORIENTED PROGRAMMING USING C++


SYNTAX HOW TO CALL OPERATOR OVERLODAED FUNCTION

SYNTAX For Unary Opertor :

X operator or operator x // X.operator()

SYNTAX For Unary Opertor for friend function

operator(x)

SYNTAX For Binary Opertor :

X .operator( y ) or x+y

SYNTAX For Binary Opertor for friend function:

Operartor (x,y)

OBJECT ORIENTED PROGRAMMING USING C++


• // UNARY OPERATOR OVERLOADING USING FRINED FUNCTION
• #include <iostream>

• using namespace std;

• class Test
• {
• private:
• int a;
• public:
• void set_a();
• void get_a();
• friend Test operator -(Test);
• };
• void Test :: set_a()

• {
• a = 10;
• }

• void Test :: get_a()


• {
• cout<< a <<"\n";
• }
• Test operator -(Test obj)
• {
• obj.a = -(obj.a);
• return obj;
• }
• int main()
• {
Test obj;
• obj.set_a();
• cout<<"The value of a is : ";
• obj.get_a();
• obj = -obj;
• cout<<"after Overloading :";
• obj.get_a();
• }

OBJECT ORIENTED PROGRAMMING USING C++


//Binary overloading using friend
class complex complex operator + (complex &obj)
{ {
int x, y; complex temp;
public: temp.x = x + obj.x;
complex() { } // default constructor temp.y = y + obj.y;
complex(int a, int b) return temp;
{ }
x=a; }; //end of class definition
y=b; int main()
} {
void display() complex c1(15,30);
{ complex c2(20,35);
cout<<x<<endl; complex c3;
cout<<y<<endl; c3 = c1+c2 ; // or c3 = c1.operator+(c2);
} c3.display();
friend complex operator+(complex &obj1, }
complex &obj2);
}; //end of class definition

OBJECT ORIENTED PROGRAMMING USING C++


Type Casting/type conversion
Typecasting is also called as type conversion

converting one data type into another data type is called type casting .

Converting smaller data type into a larger one is also called as type promotion.

Two types of type conversion:

1. Implicit Type Conversion /automatic type conversion.


2. Explicit Type Conversion

Seema Kumari,Astt. Prof 30


OBJECT ORIENTED PROGRAMMING USING C++
,SCA
implicit type conversion : The implicit type conversion is the type of conversion
done automatically by the compiler without any human effort. Hence, it is also
known as the automatic type conversion.

#include<iostream>
using namespace std;
int main()
{
int x=1;
char y='a';
cout<<x+y;

Seema Kumari,Astt. Prof 31


OBJECT ORIENTED PROGRAMMING USING C++
,SCA
Explicit Type Conversion : The conversion, which is done by the user .In other words an
explicit conversion allows the programmer to manually changes or typecasts the data
type from one variable to another type.

Syntax of the explicit type casting

(data type) expression;

OR

(data type) variable;

Seema Kumari,Astt. Prof 32


OBJECT ORIENTED PROGRAMMING USING C++
,SCA
Example

#include <iostream>
using namespace std;
int main ()
{
// declaration of the variables
int a=97;

cout <<"value of a without type casting is : "<<a <<endl ;


cout<<"value of a using explicit type casting is: "<<(char)a; //usimg explicit type casting
return 0;
}

Seema Kumari,Astt. Prof 33


OBJECT ORIENTED PROGRAMMING USING C++
,SCA
We know about Friend function

• It can access all private and protected member of


a class
• It can be call without object of the class
• It can define out side of the class scope
Rule:
Prototypes of friend function must be declare inside
the class
It can be declared either in the private or the public
part.

OBJECT ORIENTED PROGRAMMING USING C++


Overloading binary operators using friend function

Friend function takes two parameters in case when


we want to overload binary operators using
friend function
Ex:
friend A operator +(A &x, A &y);

OBJECT ORIENTED PROGRAMMING USING C++


Situation Student

regNo, Name regNo, Name


studentDetails() studentDetails()
Exam Project

regNo, Name
regNo, Name studentDetails()
studentDetails()
ambiguity arises as to which
Result data/function member would
OBJECT ORIENTED PROGRAMMING USING C++ be called?
virtual base class introduce

OBJECT ORIENTED PROGRAMMING USING C++


Compile time polymorphism Run time polymorphism

The function to be invoked is known at the compile time. The function to be invoked is known at the run time.

It is also known as overloading, early binding and static binding. It is also known as overriding, Dynamic binding and late binding.

Overloading is a compile time polymorphism where more than one method is having the same Overriding is a run time polymorphism where more than one method is having the same name, number of parameters and the type of
name but with the different number of parameters or the type of the parameters. the parameters.

It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers.

It provides fast execution as it is known at the compile time. It provides slow execution as it is known at the run time.

Created By:
Kumar Vishal
It is less flexible as mainly all the things execute at the compile time. It is more flexible as all the things execute at the run time.
(SCA), LPU
OBJECT ORIENTED PROGRAMMING USING C++
virtual base classes
• It means we are making base class as virtual
• But why ???
• In situation??? A int a

int b int c

Let’s assume (int a) B C ( int a)

int a

D int d

OBJECT ORIENTED PROGRAMMING USING C++


Situation
PlayMovie()
PlaySong()

PlayMovie() PlayMovie() PlayMovie()


PlaySong() PlaySong() PlaySong()

OBJECT ORIENTED PROGRAMMING USING C++


What’s meaning it….

OBJECT ORIENTED PROGRAMMING USING C++


Its method overriding

OBJECT ORIENTED PROGRAMMING USING C++


• Problems in method overriding
– Overriding using base class pointer compiler don’t
know about pointer which address is pointing
because address will be decided at run time when
memory will be allocated.
– To over come this problem we use virtual function
– With the help of virtual function, we can override
function at run time

OBJECT ORIENTED PROGRAMMING USING C++


Abstract Class
• Sometimes implementation of function is not
required in a base class such a class is called
abstract class.
• In such cases we have to make function as
abstract function by using virtual keyword that is
also called pure virtual function.
• A pure virtual function is declared by assigning 0
in declaration.
Example

OBJECT ORIENTED PROGRAMMING USING C++


Situation
Transportation:
Vehicle_Registration()

Himachal_Transport Karnataka_Transport Bihar_Transport


Punjab_Transport
Vehicle_Registration() Vehicle_Registration() Vehicle_Registration()
Vehicle_Registration()

PB081234 HP014567 KA023333 BR012345


OBJECT ORIENTED PROGRAMMING USING C++
Area

getArea()

getArea()
getArea()

Area = w × h
w = width Area = π × r2
h = height
OBJECT ORIENTED PROGRAMMING USING C++
Important points:

• A class is abstract if it has at least one pure virtual


function.
• If we do not override the pure virtual function in derived
class, then derived class also becomes abstract class.
• An abstract class can have constructors.
• We cannot create objects of abstract classes.

OBJECT ORIENTED PROGRAMMING USING C++


What will be the output of the following C++ code?
#include<iostream> class Person: public Mobile
using namespace std; {
class Mobile public:
void getDetails() { cout << "Blocked"; }
{
};
long int contactno;
int main()
public: {
virtual void getStatus() = 0; Person p;
Mobile() p.getDetails();
{ return 0;
contactno=9898989890; }
cout<<contactno; A. 9898989890
} B. Blocked
C.9898989890Blocked
};
D. Error

OBJECT ORIENTED PROGRAMMING USING C++


What will be the output of the following C++ code?
#include<iostream> class Person: public Mobile
using namespace std; {
class Mobile public:
void getStatus(){ cout <<"Blocked"; }
{
void getDetails(){cout<<"Kumar";}
long int contactno;
};
public: int main()
virtual void getStatus() = 0; {
Mobile() Person p;
{ p.getDetails();
contactno=9898989890; return 0;
cout<<contactno; }
} A. 9898989890
B. kumar
};
C. 9898989890kumar
D. Error
OBJECT ORIENTED PROGRAMMING USING C++
Pointer to object
• A variable that holds an address value is called a pointer
variable
• Object can also have an address , so there is also a
pointer that can point to the address of an object.
class Date
{
};
Date d1;
Date *d2;
d2=&d1;
d2->functions()
object pointer
OBJECT ORIENTED PROGRAMMING USING C++
this pointer
• It can be used to refer current class instance
variable.
Syntax:
this-> instance variable=value
Example

OBJECT ORIENTED PROGRAMMING USING C++


this pointer
This keyword represent address of current
instance of the class.
Example

OBJECT ORIENTED PROGRAMMING USING C++


this pointer
To return reference to the calling object.
Example

OBJECT ORIENTED PROGRAMMING USING C++


pointer to derived class

A pointer of one class can point to other class,


but classes must be a base and derived class,
then it is possible.
To access the variable of the base class, base
class pointer will be used.

OBJECT ORIENTED PROGRAMMING USING C++


Pointer to derived class

class base{};
class derive: public base{};
base b1,*b2;
derive d1;
b2=&d1;

OBJECT ORIENTED PROGRAMMING USING C++


What will be the output of the following C++ code?
class realme:public mobile
#include <iostream> {
using namespace std; void playRingTone()
class mobile {
{ cout<<"real me ringtone"<<endl;
public: }
void playRingTone() };
{ int main()
cout<<"mobile ring tone"<<endl; {
} mobile *mptr;
}; samsung s1;
class samsung:public mobile mptr=&s1;
{
mptr->playRingTone();
return 0;
void playRingTone()
}
{
A. mobile ring tone
cout<<"samsung ring tone"<<endl;
}
B. samsung ring tone
};
C. real me rington
D. Error

OBJECT ORIENTED PROGRAMMING USING C++


Any Query?

OBJECT ORIENTED PROGRAMMING USING C++

You might also like