You are on page 1of 22

OPERATOR OVERLAODING

• C++ allows almost all operators to be overloaded. i.e. their meaning


can be redefined for different objects.

• One cannot introduce new operators. Only existing operators can be


overloaded. e.g. one cannot create the operator +*.

• The operator keyword declares a function specifying what operator-


symbol means when applied to instances of a class. This gives the
operator more than one meaning, or "overloads" it.

• The compiler distinguishes between the different meanings of an


operator by examining the types of its operands.

• Overloaded operators are implemented as functions


return_type operator operator_symbol ( parameter-list )

List of Redefinable and Nonredefinable Operators is available on :


http://msdn2.microsoft.com/en-us/library/5tk49fh2.aspx
Example 1: (overload.cpp)
class Counter void operator ++ ( )
{ {
private: count++;
int count; }
public:
};
Counter( )
void main( )
{ {
count = 0; Counter c1, c2(5);
} cout<<“\nc1=“<<c1.getcount();
Counter(int n ) cout<<“\nc2=“<<c2.getcount();
{ c1++;
count =n; c2++;
} c2++;
int getcount ( ) cout<<“\nc1=“<<c1.getcount();
cout<<“\nc2=“<<c2.getcount();
{
}
return count;
}
Example 2 (optional):
class Counter Counter operator ++ ( )
{ {
private: count++;
Counter temp;
int count;
temp.count=count;
public: return temp;
Counter( ) }
{ };
count = 0; void main( )
} {
Counter(int n ) Counter c1, c2(5);
cout<<"\nc1="<<c1.getcount( );
{
cout<<"\nc2="<<c2.getcount( );
count = n;
c1++;
} c2++;
int getcount ( ) c2++;
{ cout<<"\nc1="<<c1.getcount( );
return count; cout<<"\nc2="<<c2.getcount( );
} c2=++c1;
cout<<“\nc2=”<<c2.getcount( );
}
Example 3 (oldist.cpp):
class Distance Distance operator + (Distance d2 )
{ {
int feet; float inches; Distance dd;
public: dd.feet = feet+ d2.feet;
Distance ( ) dd.inches = inches+d2.inches;
{ if (dd.inches >= 12.0)
feet=0; {
inches=0; dd.inches-=12.0;
} dd.feet++;
Distance (int ft, float in ) }
{ return dd;
feet = ft; }
inches=in; void getdist ( )
} {
void showdist( ) cout<<“\nEnter Feet: “; cin>>feet;
{ cout<<“\nEnter Inches ”;
cout<<feet<<“\’-”<<inches<<“\’-”; cin>>inches;
} }
};
Example 3 (oldist.cpp):
void main( )
{
Distance dist1, dist3, dist4;
dist1.getdist( );
Distance dist2(11, 6.25);
dist3 = dist1 + dist2;
dist4 = dist1 + dist2 + dist3;

cout<<“dist1=“; dist1.showdist();
cout<<“dist2=“; dist2.showdist();
cout<<“dist3=“; dist3.showdist();
cout<<“dist4=“; dist4.showdist();
}
Calling using this
object

dist 3 = dist 1 + dist 2;

Distance Operator + (Distance d2)


{ Distance dd;
dd.feet = feet + d2.feet;
dd.inches = inches + d2. inches;
if (dd.inches >= 12.0)
{ dd.inches-=12.0; dd.feet++;}
return dd; }
Example 5:
# include <iostream.h> inches+=d2.inches;
# include <conio.h> if (inches >= 12.0)
class Distance { { inches-=12.0; feet++; }
private: int feet; float inches; } };
public:
Distance ( ) void main( )
{ feet = 0; inches=0.0; } {
Distance (int ft, float in ) Distance dist1;
{ feet = ft; inches=in; } dist1.getdist( );
void getdist ( ) cout<<“dist1=“; dist1.showdist ( );
{ cout<<“\nEnter Feet: “; Distance dist2(11, 6.25);
cin>>feet; cout<<“dist2=“; dist2.showdist( );
dist1+= dist2;
cout<<“\nEnter Inches ”;
cout<<“After addition”<<endl;
cin>>inches; }
void showdist( ){
cout<<“dist1=“; dist1.showdist( );
cout<<feet<<“\’-”<<inches<<“\’-”<<endl; }
}
void operator += (Distance d2 )
{ feet+= d2.feet;
OPERATOR OVERLAODING
• Operator overloading work only with user defined objects. (NOT with
basic data types).

• Operator functions can be global or member functions. (if global, often


are friend functions).

• Ability to redefine the operators can make your program more


readable and easy to understand.

• On other hand, it can also make your program more difficult and hard
to understand.

• THUS USE SIMILAR MEANINGS.

• Use overloaded operators only when usage is obvious. Otherwise, use


a function instead of overloaded operator, since function name can
state its own purpose.
Class Assignments

1. Overload + operator , for addition purpose.

2.
• a. Write a program to calculate salary of a employee (before
taxes given the hours worked and the hourly rate. The program output
should look similar to: (USING *= OPERATOR OVERLOADING)
• b. Extend the program for calculating Monthly Salary of more
than one employee.
• c. Firm employs students who are exempted from taxes and
others who are not. Modify the program so that if an employee is not
exempt, 10% will be deducted from Salary, otherwise "NO TAXES
DEDUCTED" will be displayed.
Two program runs are shown below:

Enter hours worked by Employee 1: 45


Enter hourly rate: 10.00
Exempted: Y/N Y
Salary: $ 450.00
…………….
…………………..
Enter hours worked by Employee 2: 40
Enter hourly rate: 20.00
Exempted: Y/N N
Salary: $ 720.00
MEMORY ALLOCATION
What is memory allocation:
• The fixed amount of memory which is required by a
program to store the values of its variables and data
structures.

• In C++ there are two different types of memory


allocation that can be used to hold the content of
program variables.

• Static memory allocation


• Dynamic memory allocation
STATIC MEMORY ALLOCATION
• In C++, compiler allocate static memory for a
program.
• Static memory has fixed size and fixed location.
• The location or size of static memory do not change
during the lifetime of program.
• When a program begins to execute, there must be
some specific blocks of memory, set aside for its use.
• This memory block cannot be used by another
program.

Static Memory Allocation using Arrays


Static array of 10 integers: int myarray[10];
(This array is created at compilation time.)
EXAMPLE: (Static Memory Allocation)

void main( )
{
int myarray[ ] = {5,10,15};
void print(myarray, 3);
}
void print (int a[ ], int length)
{
for (int n=0; n<length; n++)
cout<<a[n]<<endl;
}

• The size of the array is fixed and cannot be changed at run time.
• In C++, we use normally static arrays. But the disadvantage with
the static arrays is that once we have declared the array of a
particular size, we cannot change its size when program is
running. So the solution for this problem is to use the dynamic
array allocation.
DYNAMIC MEMORY ALLOCATION
• In last program we had fixed size of memory size for
array element. But what will happen if we need
variable amount of memory, which can only be
determined during the execution time.
• Then we require DYNAMIC MEMORY.
• In case of dynamic array, the size of an array does not
know by the compiler in advanced. This dynamic
memory is allocated by the system at the runtime. To
allocate memory dynamically, we have to use pointers.
• The real power of pointers is seen when they are used
to point dynamically allocated variables.
• But the dynamic allocation does not mean that we can
create new variables names during execution time.
• It is necessary that compiler must know all the variables
identifiers at the compile time. For this reason, creating
dynamic memory involves two steps:

1. Create a statically allocated pointer. int * ptr;


2. Create dynamic space and store its address in pointer.

We use the name of pointer to refer to the dynamic memory.


So it is important to note here dynamic allocate memory
through a pointer.
• Static arrays are declared prior to execution time and are reserved
in stack memory, whereas dynamic memory are created and
released using the special C++ new and delete operators
respectively at execution time.

• In C++ to dynamically allocate memory, we use the new operator.


For Example:
new int;
new float;
• The new int is used for dynamically memory allocation for an
integer variable at runtime.

• Thus if we want to create an array of forty integers we will write


int * ptr = new int [40];

• Here ptr is an integer pointer and we are creating an array of 40


integer element.
Rule of new operator:

• new operator returns the address of the allocated


space, so we must capture this address space pointer.

• so, in the integer array dynamic memory allocation,


we will declare an integer pointer to capture the
address space pointer which will be returned by the
new operator.

• Now if array size is changed from a constant value to


any variable we can take this value from the user at
runtime.
• As we know that we never need to worry about getting rid of
statically allocated memory.

• Static variables and static arrays are automatically handled by


the compiler which has already determined their scope and their
lifetime.

• But there is a problem in Dynamic Memory Allocation that this


memory is created on the free store. If we do not release this
memory this will become the memory leak.

• Anything we will create dynamically will be ignored by the


compiler. It is necessary to de allocate this allocated memory for
the reuse.

• For this purpose, in C++ an operator delete is used to de-allocate


• To de-allocate dynamically allocate memory, apply the delete
operator to the pointer, and it will delete the dynamic memory
that the pointer is pointing to.

• It is important to note that this does not de-allocate the


pointer but the only free the dynamic memory. Syntax used for
de-allocation of an array is

delete [ ] pointer name;

• In case of objects, destructor are called.

• Dynamic array is nice as the size of the array can be


determined at runtime and then using size with the new
operator to allocate space.
Example:
class DynamicArray DynamicArray :: DynamicArray (int
{ arraysize)
private: \\ size of array is
passed as parameter
int * array;
{
/*integer type pointer holds the address of
the dynamic array which is created at the array = new int [arraysize] ;
runtime. */ /*Dynamic array is created and the address
int size; of the dynamic array is stored in an integer
pointer “array.” */
/* integer type variable tells the total
number of the elements of array. */ for (int i=0 ; i<arraysize ; i++)
public: // initializing the elements.
DynamicArray (int arraysize); array [ i ] = i ;
//Constructor size = arraysize;
~DynamicArray( ); }
//Destructor DynamicArray :: ~DynamicArray ( )
void ChangeSize (int arraysize); // to delete the dynamic array.
//To change size of array {
void PrintArray( ); delete [ ] array;
//To print the elements of the array. }
};
Example: (Contd.)
void DynamicArray :: ChangeSize(int void main( )
arraysize) {
{
DynamicArray a1(2), a2(5);
delete [ ] array;
//delete previously allocated Dynamic array.
array = new int [arraysize]; a1.PrintArray( );
// create new array. a2.PrintArray( );
for(int i=0 ; i<arraysize ; i++)
// initialization. a1.ChangeSize(7);
array [ i ] = i ;
a2.ChangeSize(10);
size = arraysize;
}
void DynamicArray :: PrintArray( )
a1.PrintArray( );
{ a2.PrintArray( );
for (int i=0 ; i<size ; i++) }
cout<< array [ i ] << ” \ t ”;
cout<<endl;
}
#include<iostream.h>
#include<conio.h>
class square
{
private: int length, width, result;
public:

square (int a, int b) { length=a; width=b; }

void print ( )
{ cout<<"The area of square is : "<<result<<endl; }

friend void area (square &sqr1);


};

void area (square &sqr1)


{ sqr1.result = sqr1.length * sqr1.width; }

void main( )
{
square sqr1( 2,3 );
area(sqr1) ;
sqr1.print();
}

You might also like