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

Unit 2function Overloading

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Unit 2function Overloading

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Unit 2:Function Overloading and Constructor

Function overloading is a feature of object-oriented programming where two or more functions can have the same
name but different parameters. When a function name is overloaded with different jobs it is called Function
Overloading. In Function Overloading "Function" name should be the same and the arguments should be different.
Function overloading can be considered as an example of a polymorphism feature in C++.
If multiple functions having same name but parameters of the functions should be different is known
asFunctionOverloading.

If uppose you have to perform addition of the given numbers but there can be any number of arguments, if you write
the function such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for
you to understand the behavior of the function because its name differs.

The parameters should follow any one or more than one of the following conditions for Function overloading:
 Parameters should have a different type
add(int a, int b)
add(double a, double b)
Programme for Function Overloading:
#include<iostream.h>
#include<conio.h>
class funover
{

float a,b;
int c;
public:
void math( float x,float y)
{
a=x;
b=y;
cout<<"sum of a and b is"<<a+b;
}
void math( int z)
{
c=z;
cout<<"square of c is :"<<c*c;
}
};
void main()
{
funover f;
f.math(3.006,4.004);
f.math(5);
getch();
}
Output:
Sum of a and b is :7.01
Square of c is:25
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used
to initialize the data members of new objects generally. The constructor in C++ has the same name as the
class or structure.

Conditions for Constructors:


• Constructor is a member function of a class, whose name is same as the class name.
• Constructor is a special type of member function that is used to initialize the data members for an
object of a class automatically, when an object of the same class iscreated.
• Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.
• Constructor do not return value, hence they do not have a return type.
Types of constructor
• Default constructor
• Parameterized constructor
• Copy constructor

1.Default constructor
Default constructor is the constructor which doesn't take any argument. It has no parameters. It is also called
a zero-argument constructor.
Program:
// Cpp program to illustrate the
// concept of Constructors
#include <iostream>
using namespace std;

class construct {
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}

O/P:
a: 10
b: 20

2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments


help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it
the way you would to any other function. When you define the constructor's body, use the parameters to
initialize the object.
// CPP program to illustrate
// parameterized constructors
#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX() { return x; }


int getY() { return y; }
};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();

return 0;
}
Output
p1.x = 10, p1.y = 15
3. Copy Constructor:
A copy constructor is a member function that initializes an object using another object of the same class. A
detailed article on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters ) for a class, a default
constructor( without parameters ) should also be explicitly defined as the compiler will not provide a default
constructor in this case. However, it is not necessary but it's considered to be the best practice to always
define a default constructor.
Copy constructor takes a reference to an object of the same class as an argument.
Sample(Sample &t)
{
id=t.id;
}
// Program of copy constructor
// Implicit copy constructor

#include<iostream>
using namespace std;

class Sample
{ int id;
public:
void init(int x)
{
id=x;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};

int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1;
obj2.display();
return 0;
}
Output
ID=10
ID=10

Destructor:

A destructor is also a special member function as a constructor. Destructor destroys the class objects created
by the constructor. Destructor has the same name as their class name preceded by a tilde (~) symbol. It is not
possible to define more than one destructor. The destructor is only one way to destroy the object created by
the constructor. Hence destructor can-not be overloaded. Destructor neither requires any argument nor returns
any value. It is automatically called when the object goes out of scope. Destructors release memory space
occupied by the objects created by the constructor. In destructor, objects are destroyed in the reverse of
object creation.
The syntax for defining the destructor within the class
~ <class-name>()
{
}
The syntax for defining the destructor outside the class
<class-name>: : ~ <class-name>(){}

#include <iostream>
using namespace std;

class Test {
public:
Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }


};
main()
{
Test t;

return 0;
}

Output
Constructor executed
Destructor executed
Characteristics of a destructor:-

1. Destructor is invoked automatically by the compiler when its corresponding constructor goes out of scope
and releases the memory space that is no longer required by the program.
2. Destructor neither requires any argument nor returns any value therefore it cannot be overloaded.
3. Destructor cannot be declared as static and const;
4. Destructor should be declared in the public section of the program.
5. Destructor is called in the reverse order of its constructor invocation

Overloading of Constructor:
#include<iostream.h>
#include<conio.h>
#include<math.h>
class col
{
int a,b;
float c;
public:
col(int x,int y)
{
a=x;b=y;
cout<<"sum of a and b is"<<a+b<<endl;
}
col(float z)
{
c=z;
cout<<"square root of c is"<<sqrt(c)<<endl;
}
col()
{
cout<<"col stands for constructor overloading";}
};
void main()
{
clrscr();
col c1(10,20);
col c2(256);
col c3;
getch();
}
Output:
Function Overloading and Ambiguity:

In Function overloading, sometimes a situation can occur when the compiler is unable to choose between two
correctly overloaded functions. This situation is said to be ambiguous.
Example 1: Call of overloaded 'test(char)' is ambiguous
How this ambiguity occurs:
Below is the C++ program to demonstrate the ambiguity.
// C++ program to implement
// the above approach
#include <iostream>
using namespace std;

// Overloaded Function with


// float type parameter
void test(float f)
{
cout << "Overloaded Function with float "
<< "parameter being called";
}

// Overloaded Function with


// double type parameter
void test(double d)
{
cout << "Overloaded Function with double "
<< "parameter being called";
}

// Driver code
int main()
{
// Overloaded Function called
// with char type value
test('a');

return 0;
}
Why ambiguity occurs:
When there is no exact type match, the compiler looks for the closest match. The closest match for "test('a');"
will be "void test(int a)", since it is not present, void test(double d) and void (float f)will cause ambiguity.
Both are valid conversions. This confusion causes an error message to be displayed and prevents the program
from compiling.
How to resolve ambiguity:
There are two ways to resolve this ambiguity:
1. Typecast char to float.
2. Remove either one of the ambiguity generating functions float or double and add overloaded function
with an int type parameter

// C++ program to implement(Typecast char to float.)

// the above approach


#include <iostream>
using namespace std;

// Overloaded Function with


// float type parameter
void test(float f)
{
cout << "Overloaded Function with float "
<< "parameter being called";
}
// Overloaded Function with
// double type parameter
void test(double d)
{
cout << "Overloaded Function with double "
<< "parameter being called";
}

// Driver code
int main()
{
// Overloaded Function called
// with char type value
// typecasted to float
test((float)('a'));

return 0;
}
o/p:
Overloaded Function with float parameter being called
C++ Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator
overloading. Operator overloading is a compile-time polymorphism. For example, we can overload an operator '+' in a
class like String so that we can concatenate two strings by just using +.
Program:

#include<conio.h>

#include<iostream.h>

class opov

int x;

public:

opov()
{

x=10;

};

void operator ++()

x++;

};

void operator--()

x--;

void show()

cout<<"x value is: "<<x<<endl;

};

void main()

opov v;

clrscr();

v++;

v. show();

v--;

v.show();
getch();

}o/p:

Operators that can be overloaded Examples

Binary Arithmetic +, -, *, /, %

Unary Arithmetic +, -, ++, —

Assignment =, +=,*=, /=,-=, %=

Bitwise & , | , << , >> , ~ , ^

De-referencing (->)

Dynamic memory allocation,


New, delete
De-allocation

Subscript []

Function call ()

Logical &, | |, !

Relational >, < , = =, <=, >=


Operator overloading using friend Function:

#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int img;
public:
Complex (int r = 0, int i = 0)
{
real = r;
img = i;
}
void Display ()
{
cout << real << "+i" << img;
}
friend Complex operator + (Complex c1, Complex c2);
};

Complex operator + (Complex c1, Complex c2)


{
Complex temp;
temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;
return temp;
}

int main ()
{
Complex C1(5, 3), C2(10, 5), C3;
C1.Display();
cout << " + ";
C2.Display();
cout << " = ";
C3 = C1 + C2;
C3.Display();
}

Points to Remember While Overloading Operator using Friend Function:


We need to remember the following pointers while working with Operator Overloading in C++ Using Friend Function.
1. The Friend function in C++ using operator overloading offers better flexibility to the class.
2. The Friend functions are not a member of the class and hence they do not have 'this' pointer.
3. When we overload a unary operator, we need to pass one argument.
4. When we overload a binary operator, we need to pass two arguments.
5. The friend function in C++ can access the private data members of a class directly.
6. An overloaded operator friend could be declared in either the private or public section of a class.
7. 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
Overloading New and Delete operator in c++
he new and delete operators can also be overloaded like other operators in C++. New and Delete operators
can be overloaded globally or they can be overloaded for specific classes.
 If these operators are overloaded using member function for a class, it means that these operators are
overloaded only for that specific class.
 If overloading is done outside a class (i.e. it is not a member function of a class), the overloaded 'new' and
'delete' will be called anytime you make use of these operators (within classes or outside classes). This
is global overloading.
The syntax for overloading the new operator :
void* operator new(size_t size);
The overloaded new operator receives size of type size_t, which specifies the number of bytes of memory to
be allocated. The return type of the overloaded new must be void*.The overloaded function returns a pointer
to the beginning of the block of memory allocated.
Syntax for overloading the delete operator :
void operator delete(void*);
The function receives a parameter of type void* which has to be deleted. Function should not return
anything.
NOTE: Both overloaded new and delete operator functions are static members by default. Therefore, they
don't have access to this pointer .
Overloading new and delete operator for a specific class:

// Overloading new and delete operator


// for a specific class
#include<iostream>
#include<stdlib.h>

using namespace std;


class student
{
string name;
int age;
public:
student()
{
cout<< "Constructor is called\n" ;
}
student(string name, int age)
{
this->name = name;
this->age = age;
}
void display()
{
cout<< "Name:" << name << endl;
cout<< "Age:" << age << endl;
}
void * operator new(size_t size)
{
cout<< "Overloading new operator with size: " << size << endl;
void * p = ::operator new(size);
//void * p = malloc(size); will also work fine

return p;
}

void operator delete(void * p)


{
cout<< "Overloading delete operator " << endl;
free(p);
}
};

int main()
{
student * p = new student("Rahul", 23);

p->display();
delete p;
}
o/p:
Overloading new operator with size: 40
Name:Rahul
Age:23
Overloading delete operator

You might also like