0% found this document useful (0 votes)
6 views

CPP Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

CPP Unit 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

CM3104

Unit 4 - Operator Overloading, Polymorphism And


Type Conversion

4.1 Operator Overloading: Introduction, defining operator overloading,


overloading unary operators, overloading binary operators, overloading
binary operators using friends, manipulation of strings using operators, rules
of overloading operators.
4.2 Polymorphism: Introduction, why polymorphism is useful, syntax and
example.
4.3 Type Conversion: Introduction, basic to class type, class to basic type, one
class to another type, data conversion example.
****************************************************************
Overloading Binary Operators using Friends
✓ The Friend function in C++ using operator overloading offers better
flexibility to the class.
✓ The Friend functions are not a member of the class and hence they do not
have ‘this’ pointer.
✓ When we overload a unary operator, we need to pass one argument.
When we overload a binary operator, we need to pass two arguments.
✓ The friend function in C++ can access the private data members of a class
directly.
✓ An overloaded operator friend could be declared in either the private or
public section of a class.
✓ When redefining the meaning of an operator by operator overloading the
friend function, we cannot change its basic meaning. For example, we
cannot redefine minus operator + to multiply two operands of a user-
defined data type.
✓ Friend function are more useful in operator overloading
✓ They are more flexible then member function,
✓ The different between member function and friend function is that
member function arguments explicitly.
✓ The friend functions needs the parameter should be explicitly fast.
✓ Friend function requires two operands to be passed an arguments

1|Page 186_Shraddha Keshao Bonde_N2


CM3104

✓ Syntax - friend return type operator (variable!, operator symbol variable?)

Operator Overloading
✓ A symbol that is used to perform an operation is called an operator. It is
used to perform an operation with constants and variables.
✓ A programmer cannot build an expression without an operator.
✓ The compiler knows how to perform various operations using operators
for the built-in types, however, for the objects those are instance of the
class, the operation routine must be defined by the programmer.
✓ Keyword operator - The keyword operator defines a new operation (or)
action to the operator.
✓ In C++, we can change the way operators work for user defined types like
objects and structures. This is known as operator overloading.

Defining Operator Overloading


✓ To define an additional task to an operator, we must specify what it means
in relation to the class to which the operator is applied . This is done with
the help of a special function called operator function, which describes
the task.
✓ Syntax:
return-type operator operatorsymbol(parameter list){statement 1; …..
statement n;
}
✓ Here, returnType is the return type of the function.
operator is a keyword.
operatorsymbol is the operator we want to overload.
Like: +, <, -, ++, etc.
parameters is the arguments passed to the function.
✓ The process of overloading involves following steps:
1. Create a class which is to be used with overloading operation.
2. Declare the operator function operator symbol() in the public part of
the class.
3. It may be a member function or a friend function.
4. Here symbol is the operator to be overloaded.
5. Define the operator function to implement the required operations
6. Arguments may be either by value or by reference.
q
Manipulation of Strings using Operators

2|Page 186_Shraddha Keshao Bonde_N2


CM3104

✓ String manipulation basically refers to the process of handling and


analyzing strings.
✓ It involves various operations concerned with modification/concat and
comparison of strings to use and change its data.
✓ C++ allows us to manipulate strings using the concept of operator
overload.
✓ For example, we can override-
• the + operator to concatenate two strings.
• the = = operator to compare two strings.

Rules of Operators Overloading


✓ Only existing operators can be overloaded.
✓ We cannot change basic meaning of an operator.
✓ Overloaded operator must follow minimum characteristics that of original
operator.
✓ Precedence of an operator cannot be changed
✓ Associativity of an operator cannot be changed
✓ No new operators can be created.
✓ No overloading operators for built-in types
✓ The overloaded operator must have at least one operand that is of user
defined data type
✓ Following operators can’t be overloaded:
• Class member access operators (., .*)
• Scope resolution operator (::)
• Size operator (sizeof )
• Conditional operator (?:)

Operator Overloading Example


✓ The keyword "operator", followed by a symbol, defines a new
(overloaded) action of the given operator.
✓ Note: We cannot use operator overloading for fundamental data types like
int, float, char and so on.
✓ Example :
• void operator ++();
• void operator --();
• void operator +();
• void operator -();
• void operator ++(num);

3|Page 186_Shraddha Keshao Bonde_N2


CM3104

• void operator -(num,num);

Overloading Unary Operators


✓ An unary operator means, an operator which works on single operand.
For example, ++ is an unary operator, it takes single operand (c++).
✓ So, when overloading an unary operator, it takes no argument (because
object itself is considered as argument).
✓ Syntax for Unary Operator (Inside a class)
return-type operator operatorsymbol( ){
//body of the function
}
✓ Syntax for Unary Operator (Outside a class)
return-type classname::operator operatorsymbol( ){//body of the function
}
✓ Example 1:-
void operator++(){counter++; }
✓ Example 2:-
void complex::operator-(){
real=-real;
img=-img;
}

Overloading Binary Operators


✓ A binary operator means, an operator which works on two operands. For
example, + is an binary operator, it takes single operand (c+d).
✓ So, when overloading an binary operator, it takes one argument (one is
object itself and other one is passed argument).
✓ A binary operator + can be overloaded to add two objects rather than
adding two variables.
✓ While overloading binary operators using member function, the arg-list
will contain one parameter.
✓ Syntax for Binary Operator (Inside a class)
return-type operator operatorsymbol(argument)
{
//body of the function
}
✓ Syntax for Binary Operator definition (Outside a class)return-type
classname::operator operatorsymbol(argument){
//body of the function
4|Page 186_Shraddha Keshao Bonde_N2
CM3104

All operators that can be overload

Polymorphism – Introduction

Polymorphism

Compile time polymorphism Run Time Polymorphism

Function Operator Virtual Functions


overloading overloading

✓ Polymorphism comes from the Greek words “poly” and “morphism”.


“poly” means many and “morphism” means form i.e.. many forms.

5|Page 186_Shraddha Keshao Bonde_N2


CM3104

✓ Polymorphism means the ability to take more than one form. Advantage
of this is you can make an object behave differently in different
situations, so that no need to create different objects for different
situations.
✓ Polymorphism can be achieved with the help of
✓ Overloading and Overriding concepts and it is classified into compile
time polymorphism and Runtime polymorphism.
✓ Function with same name but different arguments .
✓ Functioning is different.
✓ Example : add(int a, int b) add(int a, int b, int c)
add(float a, float b) add(float a, float b, float c)

Compile Time Polymorphism


✓ Compile time(Static) polymorphism in C++ is invoked during the compile
time of the program. There are two ways to achieve compile-time
polymorphism in C++:
✓ Function/Method Overloading – Function overloading allows you to
write multiple functions with the same name but different parameter lists
✓ Operator Overloading - Operator overloading enables operators like +, -,
*, /, and others to be redefined for user-defined data types.
✓ Advantage - Compile-time polymorphism can help you write cleaner, more
efficient code by allowing you to reuse function names and reduce
redundancy. It also helps catch errors at compile time instead of at runtime,
which can save you time and effort in debugging.

Run Time Polymorphism


✓ In Run-time Polymorphism, functions are called at the time of the
program execution/runtime, therefore it is also called late binding or
dynamic binding.
✓ The Run-time polymorphism can be achieved by-
✓ Function/Method Overriding - Function overriding occurs when a
derived/child class and base/parent class both contain a function having
the same name.
✓ Virtual function- Virtual function is another way of implementing run-
time polymorphism. A virtual function is a member function which is
declared using a virtual keyword in the base class. A virtual functions is
used to make sure that the correct function is called, regardless of the

6|Page 186_Shraddha Keshao Bonde_N2


CM3104

reference type used to call the function, the appropriate function is


invoked for an object.
Differentiate compile time & runtime polymorphism

Why Polymorphisms useful?


✓ More generic and loosely coupled code.
✓ It reduces redundancy
✓ It helps you write the code consistently.
✓ For example, suppose you want to find the area of a circle and a
rectangle. For that, your first approach will be to create a base class that
will deal with the type of polygon. This base class contains two derived
classes, one for the circle and another one for the rectangle. Now, instead
of declaring two separate functions with separate names in both the
derived classes to calculate the area of each polygon, you can just declare
one function in the base class and override it in the child classes to
calculate the area.
✓ In this way, you increase the code consistency using polymorphism.

Type Conversion or Data Conversion


7|Page 186_Shraddha Keshao Bonde_N2
CM3104

✓ C++ provides mechanism to perform automatic type conversion if all


variable are of basic type.
✓ For user defined data type programmers have to convert it by using
constructor or by using casting operator.
✓ The type conversion is automatic as far as data types involved are
built/basic in types by the compiler.
✓ The compiler has no knowledge about the user-defined datatype and
about their conversion of other data type
✓ We can also use the assignment operator in case of objects to copy values
of all data members of right hand object to the object on left hand.
✓ The objects in this case are of same data type. But of objects are of
different data types we must apply conversion rules for assignment.
✓ There are three types of situations that arise where data or type
conversion are between incompatible types.
1. Conversion from built in/basic type to class type.
2. Conversion from class type to built in type.
3. Conversion from one class type to another class type.

Basic To Class Type


✓ In this type the left hand operand of (=) equal sign if always the class type.
The right hand operand is always basic type.
✓ The Conversion can be done by the compiler with the help of build routine
or by applying type casting.
✓ It uses constructors for changing the Basic type to class type
✓ The conversion from a base type to a Class type is easy to implement. To
initialize objects, it uses constructor.
✓ The constructor used in the type conversion takes a single argument whose
type is to be converted.
✓ We can also get the same output by implementing with overload = operator.

Class Type To Basic Data Type


✓ The constructor functions do not support conversion from a class to basic
type.
✓ C++ allows us to define a overloaded casting operator that convert a class
type data to basic type.
✓ The general form of an overloaded casting operator function, also
referred to as a conversion function, is:
operator typename ( ){ //Program statement }
✓ This function converts a class type data to typename.
8|Page 186_Shraddha Keshao Bonde_N2
CM3104

✓ In this type of conversion the programmer explicitly specify about the


conversion.
✓ There instruction are return in a member function. This type of
conversion also known as over loading of type cast operators.
✓ In this type the left hand operand is Basic data type the right hand
operand is class type.
✓ The compiler does not have any knowledge about the user – defined
(class) data type using class.
✓ The casting operator should satisfy the following conditions.• It must be a
class member.
• It must not specify a return type.
• It must not have any arguments. Since it is a member function, it is
invoked by the object and therefore, the values used for, Conversion
inside the function belongs to the object that invoked the function. As a
result function does not need an argument.
✓ In the string example discussed earlier, we can convert the object string to
char* as follows:
string:: operator char*( ){
return (str) ;
}

One Class Type To Another Class Type


✓ One class type can be converted to another class type in two ways
1. using constructor- single-argument constructor function.
• The argument belongs to the source class and is passed to the
destination class for conversion.
• Therefore the conversion constructor must be placed in the
destination class.
2. using casting operator – syntax- Operator typename( ).
• when a class needs to be converted, a casting operator function can
be used.
• The conversion takes place in the source class and the result is
given to the destination class object.
✓ Which way to use, depends upon where we want the type conversion
function to be located, whether in the source class (right object i.e Obj2 )
or in the destination class (left object i.eObj1 ) .Example- Obj1 = Obj2 ;
//Obj1 and Obj2 are objects of different classes.
************************************************************

9|Page 186_Shraddha Keshao Bonde_N2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy