0% found this document useful (0 votes)
2 views25 pages

meena

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 25

Unit -2

Functional overloading & operator overloading

Functional 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++. In function overloading, the
function is redefined by using either different types of arguments or
a different number of arguments. It is only through these differences
compiler can differentiate between the functions.

Example:

#include <iostream>

using namespace std;


class Cal {
public:
static int add(int a,int b){
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}
};

int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}

Default arguments in C++:


In a function, arguments are defined as the values passed when a
function is called. Values passed are the source, and the receiving
function is the destination

A default argument is a value in the function declaration


automatically assigned by the compiler if the calling function does not
pass any value to that argument.

Characteristics for defining the default arguments:

o The values passed in the default arguments are not constant. These
values can be overwritten if the value is passed to the function. If
not, the previously declared value retains.

o During the calling of function, the values are copied from left to
right.

o All the values that will be given default value will be on the right.

Example:

#include<iostream>
int sum(int x, int y, int z=0, int w=0) // Here there are two values in
the default arguments
{ // Both z and w are initialised to zero
return (x + y + z + w); // return sum of all parameter values
}
int main()
{
cout << sum(10, 15) << endl; // x = 10, y = 15, z = 0, w = 0
cout << sum(10, 15, 25) << endl; // x = 10, y = 15, z = 25, w =
0
cout << sum(10, 15, 25, 30) << endl; // x = 10, y = 15, z = 25, w
= 30
return 0;
}

Constructor overloading :
Constructor is a member function of a class that is used to initialize
the objects of the class. Constructors do not have any return type and are
automatically called when the object is created.

Characteristics of constructors:

o The name of the constructor is the same as the class name

o No return type is there for constructors

o Called automatically when the object is created

o Always placed in the public scope of the class

o If a constructor is not created, the default constructor is created


automatically and initializes the data member as zero

o Declaration of constructor name is case-sensitive

o A constructor is not implicitly inherited

Types of constructors
There are three types of constructors -

o Default constructor :
A default constructor is one that does not have function
parameters. It is used to initialize data members with a value. The
default constructor is called when the object is created.

Example:

#include <iostream>
class construct // create a class construct
{
public:
int a, b; // initialise two data members
construct() // this is how default constructor is created
{
// We can also assign both values to zero
a = 10; // intialise a with some value
b = 20; // initialise b with some value
}
};
int main()
{
construct c; // creating an object of construct calls defualt
onstructor
cout<< "a:" <<c.a<<endl
<< "b:" <<c.b; // print a and b
return 1;
}
o Parameterized constructor :

A non-parameterized constructor does have the constructor


arguments and the value passed in the argument is initialized to its
data members. Parameterized constructors are used in constructor
overloading.

Example:

#include <iostream>

class Point // create point class


{
private:
int x, y; // the two data members of class Point
public:
Point(int x1, int y1) // create paramterised Constructor and initialis data m
ember
{
x = x1; // x1 is now intialised to x
y = y1; // y1 is now intialised to y
}
intgetX()
{
return x; // to get the value of x
}
intgetY()
{
return y; // to get the value of y
}
};
int main()
{
Point p1(10, 15); // created object for paramterised constructor
cout<< "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); // print
and y
return 0;
}

o Copy constructor :

Copy constructor initializes an object using another object of


the same class.

Syntax:

class_name(constclassname&old_object).

Example:

#include <iostream>
class Point // create point class
{
private:
int x, y; // data members of the class
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
} // parameterised constructor

// Copy constructor
Point(const Point& p1) // initialisation according to syntax
{
x = p1.x;
y = p1.y;
}
intgetX() { return x; } // return value of x
intgetY() { return y; } // return valur of y
};
int main()
{
Point p1(10, 15); // call parameterised constructor
Point p2 = p1; // call Copy constructor
// use getter and setter to print x and y
cout<< "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout<< "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}

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 overloading is used to overload or
redefines most of the operators available in C++. It is used to
perform the operation on the user-defined data type. For example,
C++ provides the ability to add the variables of the user-defined
data type that is applied to the built-in data types.

The advantage of Operators overloading is to perform different operations


on the same operand.

Operator that cannot be overloaded are as follows:

o Scope operator (::)

o Sizeof

o member selector(.)

o member pointer selector(*)

o ternary operator(?:)

Syntax of Operator Overloading:

return_type class_name : : operator op(argument_list)


{
// body of the function.
}

Where the return type is the type of value returned by the


function.
class_name is the name of the class.
operator op is an operator function where op is the operator being
overloaded, and the operator is the keyword.

Rules for Operator Overloading:


o Existing operators can only be overloaded, but the new operators
cannot be overloaded.

o The overloaded operator contains atleast one operand of the user-


defined data type.

o We cannot use friend function to overload certain operators.


However, the member function can be used to overload those
operators.

o 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.

o 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.

Example:

#include <iostream>
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++()
{
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}

Overloading the Operator with Member Functions:


The Operator is handled as a class member when you
overload an operator with a member function. According to this, a
class member that defines the operator function must be one of the
operands. Any compatible type, including additional user-defined
types, may be used for the other operand.

The general syntax for utilizing a member function to overload


an operator is as follows:

return_type operator op(parameters) {


// Define the behavior of the operator
// You can access the current object using 'this' pointer
}

Here, 'op' represents the Operator you want to overload (e.g., '+', '-', '*',
'/'), and 'parameters' represent the Operator's operands. The 'return_type'
specifies the type of value the Operator should return.
Example:

class Vector {
Public:
Vector(int x, int y) : x(x), y(y) {}

// Overloading the '+' operator using a member function


Vector operator+(const Vector& other) {
return Vector(this->x + other.x, this->y + other.y);
}
Private:
int x, y;
};

The addition of the relevant components of two 'Vector' objects is


accomplished in this example via the '+' Operator, which is overloaded as
a member function. A brand-new 'Vector' object is the outcome.

Operator Overloading with Friend Functions:


Another method for overloading operators with non-member
functions designated as friends inside the class is friend functions.
Although friend functions are not class members, they can access
the class's private members.

The general syntax for utilizing a friend function to


overload an operator is as follows:

friend return_type operator op(parameters);

The function is declared a 'friend' of the class with this syntax, enabling it
to access its private members. The remaining portions of the grammar
resemble member function overloading.

Let's now talk about the benefits and applications of Operator overloading
with buddy functions:
Benefits of Overloading Operators with Friend Functions:

o Symmetry:

When overloading binary operators, you can achieve


symmetric behaviour using friend functions. With member functions,
you can only access the data of the currently selected object, which
might occasionally result in asymmetry. Since friend functions can
access both operands' private members, the behaviour is
guaranteed to be symmetric.

o Non-Member Function:

Friend functions can overload operators for user-defined


types without altering the class declaration because they are not
class members. This is helpful when you need help editing the
original class.

o Global Functions:

Friend functions are global because they are defined outside


the class. This promotes code reuse because they can be used for
multiple classes or even different projects.

o Enhanced Readability:

When dealing with complex expressions involving several


objects and operators, buddy functions sometimes produce more
legible code.

o Flexibility:
When choosing which operators to overload, friend functions
offer flexibility. Without being constrained by the member functions
of the class, you can decide to overload only the operators that
make sense for your class.

Use Cases for Friend Functions to Reduce Operator Overload


Operator overloading with friend functions is more appropriate in
some situations, even if Operator overloading with member functions is
frequently the better option for simple classes:

o Mathematical Operations:

Operator overloading with buddy functions can result in more


symmetrical and natural behaviour when dealing with mathematical
classes like complex numbers, matrices, or vectors.

o Overloading External Types:

Because you cannot change the original class definitions,


buddy functions are required when you need to overload operators
for built-in or external types (like 'int', 'double', or 'std::string') to
operate with your custom classes.

o Cross-Class actions:

You can use friend functions to execute actions between


objects of different classes without breaking encapsulation.

Now that we are familiar with the fundamentals of Operator overloading


with buddy functions let's see how to put them into practice.
Operator Overloading with Friend Functions: Implementation
Steps:
It would be best if you did the following actions to overload an operator
using a friend function:

o Create the class in which the Operator should be overloaded.

o Declare the operator function inside the class as a friend. The friend
function can now access the class's private members.

o Implement the friend function and provide the Operator's behavior.

o With class objects, treat the overloaded Operator as if it were a


built-in operator.

Example :
Adding a Friend Function to the '+' Operator:

#include <iostream>
class Complex {
Public:
Complex(double real, double image) : real(real), imag(imag) {}
// Declare the '+' operator as a friend
friend Complex operator+(const Complex& c1, const Complex c2);
// Display the complex number
void display() const {
std::cout << real << " + " << imag << "i" << std::endl;
}
Private:
double real, imag;
};
// Define the '+' operator using a friend function
Complex operator+(const Complex& c1, const Complex& c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main() {
Complex c1(2.0, 3.0);
Complex c2(1.5, 2.5);
// Use the overloaded '+' operator
Complex sum = c1 + c2;
std::cout << "Sum: ";
sum.display();
return 0;
}

[ ] operator overloading:
The subscript operator [] is normally used to access array
elements. This operator can be overloaded to enhance the existing
functionality of C++ arrays.

Following example explains how a subscript operator [] can be


overloaded.

// CPP program to demonstrate []

// operator

#include <iostream>

int main()
{

char name[] = "Ramswarup Tushar Nilesh Subhash";

// Both of the statement prints same thing

cout << name[5] << endl;

cout << 5 [name] << endl;

return 0;

( )operator overloading:
The function call operator () can be overloaded for objects of
class type. When you overload ( ), you are not creating a new way
to call a function. Rather, you are creating an operator function that
can be passed an arbitrary number of parameters.

Example:

// C++ program to illustrate the

// above concepts

#include <bits/stdc++.h>

#include <iostream>

#define N 3

#define M 3

// Matrix Class

class Matrix {

private:
int arr[N][M];

public:

// Overloading of input stream

friend istream& operator>>(

istream&, Matrix&);

// Overloading of output stream

friend ostream& operator<<(

ostream&, Matrix&);

int& operator()(int, int);

};

// Function to overload the input

// ">>" operator

istream& operator>>(istream& cin,

Matrix& m)

int x;

for (int i = 0; i < N; i++) {

for (int j = 0; j < M; j++) {

// Overloading operator()

// to take input

cin >> m(i, j);

}
}

return cin;

// Function to overload the output

// "<<" operator

ostream& operator<<(ostream& cout,

Matrix& m)

for (int i = 0; i < N; i++) {

for (int j = 0; j < M; j++) {

// Overloading operator() to

// take input m.operator()(i, j);

cout << m(i, j) << " ";

cout << endl;

return cout;

// Function to call the operator

// function to overload the operators

int& Matrix::operator()(int i, int j)

{
return arr[i][j];

// Driver Code

int main()

Matrix m;

printf("Input the matrix:\n");

// Compiler calls operator >> and

// passes object cin and object m

// as parameter operator>>(cin, m);

cin >> m;

printf("The matrix is:\n");

// Compiler calls operator << and

// passes object cout and object m

// as parameter operator<<(cin, m);

cout << m;

return 0;

->Operator overloading:
The class member access operator (->) can be overloaded but it is
bit trickier. It is defined to give a class type a "pointer-like" behavior. The
operator -> must be a member function. If used, its return type must be a
pointer or an object of a class to which you can apply.

The operator-> is used often in conjunction with the pointer-


dereference operator * to implement "smart pointers." These pointers are
objects that behave like normal pointers except they perform other tasks
when you access an object through them, such as automatic object
deletion either when the pointer is destroyed, or the pointer is used to
point to another object.

The dereferencing operator-> can be defined as a unary postfix operator.


That is, given a class −

class Ptr {
//...
X * operator->();
};
Objects of class Ptr can be used to access members of class X in a very
similar manner to the way pointers are used.
void f(Ptr p ) {
p->m = 10 ; // (p.operator->())->m = 10
}

Syntax:
class ClassName
{
// ...

// operator function
ClassName* operator->()
{
// operator function body
// ...

return this; // return pointer to class object


}
};

Example:

#include <iostream>
class Double
{
public:
double d; // internal variable

// operator function, which overloads operator ->


Double* operator->()
{
return this; // return a pointer to the class
}
};

void main()
{
// access operator overload by pointer ->
Double D; // instance of class D
double x;

D.d = 3.85;

// invoke the operator function operator->()


x = D->d;

// another access method


x = D.d; // x = 3.85
cout << "x = " << x;
}

operator overload ‘ , ‘ (comma). Operator function operator,()


In C++, the operator ‘ , ‘ may be overloaded. When the operator ‘ , ‘ is
overloaded in the class, the operator function operator,() must be declared. Any
code can be placed in the body of an operator function. If desired, the ‘ , ‘ operator
can perform any non-standard operations on objects of a class.
In the standard case, the operator ‘ , ‘ is used in the assignment operation as follows
obj1 = (obj2, obj3, ..., objN);

where obj1, …, objN – instances of some class.


In the case of the standard use of the operator ‘ , ‘ the following features should be
taken into account:
 the operator ‘ , ‘ is considered binary. Therefore, the operator
function operator,() takes one parameter;
 when using the overloaded operator ‘ , ‘ in the assignment operation,
the last argument is taken into account (this argument is the result of
the operation). All other arguments are ignored.
In general, when the operator is overloaded, the class has the following form
class ClassName
{
// ...

// operator function that overloads the operator ','


ClassName operator,(ClassName obj)
{
// ...
}
};

Type Casting or type conversion:

This section will discuss the type casting of the variables in the C++
programming language. Type casting refers to the conversion of one data
type to another in a program. Typecasting can be done in two ways:
automatically by the compiler and manually by the programmer or user.
Type Casting is also known as Type Conversion.

int num = 5;
float x;
x = float(num);
x = 5.0

Implicit Type Casting or Implicit Type Conversion

o It is known as the automatic type casting.


o It automatically converted from one data type to another without
any external intervention such as programmer or user. It means the
compiler automatically converts one data type to another.
o All data type is automatically upgraded to the largest type without
losing any information.
o It can only apply in a program if both variables are compatible with
each other.

Example:
#include <iostream>
int main ()
{
short x = 200;
int y;
y = x;
cout << " Implicit Type Casting " << endl;
cout << " The value of x: " << x << endl;
cout << " The value of y: " << y << endl;

int num = 20;


char ch = 'a';
int res = 20 + 'a';
cout << " Type casting char to int data type ('a' to 20): " << res << en
dl;
float val = num + 'A';
cout << " Type casting from int data to float type: " << val << endl;
return 0;
}

Explicit Type Casting or Explicit Type Conversion:

o It is also known as the manual type casting in a program.


o It is manually cast by the programmer or user to change from one
data type to another type in a program. It means a user can easily
cast one data to another according to the requirement in a program.
o It does not require checking the compatibility of the variables.
o In this casting, we can upgrade or downgrade the data type of one
variable to another in a program.
o It uses the cast () operator to change the type of a variable.

Syntax of the explicit type casting:

(type) expression;

type:
It represents the user-defined data that converts the given
expression.

expression:

It represents the constant value, variable, or an expression whose


data type is converted.

For example, we have a floating pointing number is 4.534, and


to convert an integer value, the statement as:

int num;
num = (int) 4.534; // cast into int data type
cout << num;

When the above statements are executed, the floating-point value will be
cast into an integer data type using the cast () operator. And the float
value is assigned to an integer num that truncates the decimal portion
and displays only 4 as the integer value.

Example:

#include <iostream>
int main ()
{
// declaration of the variables
int a, b;
float res;
a = 21;
b = 5;
cout << " Implicit Type Casting: " << endl;
cout << " Result: " << a / b << endl; // it loses some information

cout << " \n Explicit Type Casting: " << endl;


// use cast () operator to convert int data to float
res = (float) 21 / 5;
cout << " The value of float variable (res): " << res << endl;

return 0;
}

You might also like