1 / 30

Overloading of new and delete Operators

Overloading of new and delete Operators. To handle memory resource in a customized way, the memory allocation operators new and delete can be overloaded. It helps the programmer to gain full control over the memory resource and to handle resource crunch errors such as Out of Memory.

campbellg
Télécharger la présentation

Overloading of new and delete Operators

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Overloading of new and delete Operators To handle memory resource in a customized way, the memory allocation operators new and delete can be overloaded. It helps the programmer to gain full control over the memory resource and to handle resource crunch errors such as Out of Memory. An application that overload new and delete operators by itself, can easily detect memory leaks (improper usage).

  2. C++ handles the type conversion in an expression involving operands of built-in data types • (i.e.) if expression with different data types, then compiler promotes all the operands to the data type of the largest operand. • Assignment operation, is also carried out in the same way, by assigning the data type of the operand to the right hand side is automatically converted to the data type of the variable on its left.

  3. But, in the real world application, we can’t say that the expression is of combination of simple operators. An expression can involve user-defined data types such as classes. But C++ compiler cannot handle the type conversion in the expression involving user-defined data type. Then HOW ??????????

  4. One approach is by using the concept of CONVERSION MECHANISM to handle the type conversions for the user-defined data types. • How to handle, by what means??? • Type conversion can be achieved by using either • Constructor (OR) • Appropriate conversion function.

  5. Types of conversion To enhance the conversion between built-in data type with user – defined data types following three types of conversion are involved: Basic type to class type Class type to basic type One class type to another class type

  6. Basic Type to Class Type This conversion is accomplished by defining a constructor of the class that accepts an argument of any basic type, which is to be converted to class type. To understand the concept of conversion, consider the below example.

  7. #include <iostream> #include <conio.h> using namespace std; class measurement { int meter; int cm; public: measurement() { meter =0; cm = 0;} measurement(int i) { meter = i*1000; cm = i*100000; } void display() { cout<<"\n\n The meter : "<<meter <<"m"; cout<<"\n The centimeter : "<<cm <<"cm"; } }; int main() { measurement r1; int km = 2; r1 = km; // implicit call to the //constructor cout<<" The measurements are "; r1.display(); getch(); }

  8. OUTPUT: The measurements are The meter : 2000m The centimeter : 200000cm

  9. Class Type to Basic Type Some times a situation may occur that a class type needs to be converted to a basic type. As done previous, the conversion cant be done using the constructor since, it requires a class object on the left-side of the type conversion. For such situation “ Conversion function” , an overloaded casting operator must be defined.

  10. Let us know about the conversion function • Conversion function is a special member function that specifies the implicit conversion of a class object to another type. • The syntax to define the conversion function inside the class is operator data_type() { // function body } Let us consider this example to know about it some more………………

  11. #include <iostream> #include <conio.h> using namespace std; class rectangle { int len; int br; public: rectangle() { } void getdata() { cout<<"Enter value for length : "; cin>>len; cout<<"Enter value for breadth: "; cin>>br; } void display() { cout<<"\n\n The length : "<<len; cout<<"\n The breadth : "<<br; } //overloaded int cast operator int(){ int r; r = len * br; return r; } }; int main() { rectangle r1; r1.getdata(); r1.display(); int area; area = r1; // call the operator int() to cast our class to int. cout<<"\n Area of rectangle is : "<<area<<" cm2"; getch(); }

  12. OUTPUT: Enter value for length : 12 Enter value for breadth: 34 The length : 12 The breadth : 34 Area of rectangle is : 408 cm2

  13. Point to remember while defining a conversion function The conversion function must be a non-static member function of the class. The conversion function cannot have an argument list or a return type. Like a constructor, the conversion function can also be called explicitly. The complier implicitly invokes the conversion function whenever a class object present on the right-hand side of the assignment statement does not match with the data type of the variable present on the left-hand side of the assignment statement

  14. Class Type to Another Class Type • When one class type is to be converted into another class type, the class type (object) that appears on the right-hand side is known as the source class and the other side is known as destination class. • Conversion of one class type to another can be handled by using • Constructor (OR) • Conversion function

  15. However , if the constructor is used for conversion, it must be defined in the destination class. Let us explain this with an example program using constructor. In this example, the conversion of US currency to INR currency is handled using class to class conversion by means of constructor (or) conversion function

  16. #include <iostream> using namespace std; class CUR_IND // destination class { int in; public: CUR_IND() // constructor defined in destination class { in =0; } void putvalue (int w) { in = w; } void display() { cout<<"Currency in indian Rupees :" << in <<endl; } };

  17. class CUR_US //source class { int us; public: CUR_US (int n) //parameterised constructor { us = n; } operator CUR_IND () // conversion function present in // source class of the destination class { CUR_IND ci; int ru = us * 65; ci.putvalue(ru); return ci; } void display() { cout<<"currency of US "<< us <<endl; } };

  18. int main() { CUR_US cu(100); CUR_IND ci; ci = cu ; // implicit call to conversion function // ci = CUR_IND(cu); // explicit call to conversion function cu.display(); ci.display(); return 0; }

  19. OUTPUT: currency of US 100 Currency in Indian Rupees :6500 Press any key to continue . . .

  20. Note: The use of both the constructor and the casting operator function for the same type conversion should be avoided, in order to prevent ambiguity in the function call.

  21. Class Diagram for number of classroom problem

  22. Source Code for number of class room problem // Program to find minimum number of classrooms required for the institution #include<iostream> using namespace std; class Classroom { int no_of_classroom; public: Classroom(){no_of_classroom = 1;} int getClassroomCount() { return no_of_classroom; } void operator++() { no_of_classroom += 1; } void operator--() { no_of_classroomm -= 1; } };

  23. class Batch { int startTime, endTime; public: int getStartTime() { return startTime; } int getEndTime() { return endTime; } void setStartTime(int n) { startTime = n; } void setEndTime(int n) { endTime = n; } //overloaded < operator for sorting bool operator < (const Batch bt) { if(startTime < bt.endTime) return true; else return false; } friend istream& operator>> (istream &, Batch&); }; istream& operator>> (istream &input, Batch &bt) { input >> bt.startTime >> bt.endTime; return input; }

  24. void sortBatchTimes(Batch bt[], int n) { int temp,i,j; for(i=n-1;i>0;i--) { for(j=1;j<=i;j++) { if(bt[j-1].getStartTime() > bt[j].getStartTime()) { temp = bt[j-1].getStartTime(); bt[j-1].setStartTime(tr[j].getStartTime()); bt[j].setStartTime(temp); } } } for(i=n-1;i>0;i--) { for(j=1;j<i;j++) { if(bt[j-1].getEndTime() > bt[j].getEndTime()) { temp = bt[j-1].getEndTime(); bt[j-1].setEndTime(tr[j].getEndTime()); bt[j].setEndTime(temp); } } } }

  25. int findClassroom(Batch bt[], int n) { sortBatchTimes(bt, n); Classroom cr; int result = 1, i = 1, j = 0; while(i<n && j<n) { if(bt[i] < bt[j]) { ++cr; i++; if(cr.getClassroomCount() > result) result = cr.getClassroomCount(); } else { - -cr; j++; } } return result; }

  26. int main() { int n = 6,i; Batch batch[n]; for(i=0; i<n; i++) { cout << "Enter Batch " << i+1 <<"'s start time and end time"; cin >> batch[i]; } cout << "\nMinimum Number of Class rooms Required=" << findClassroom(batch, n)<<endl; return 0; }

  27. In-lab Program: Job Sequencing Problem Given an list of jobs where every job has a deadline and associated profit if the job is finished before the deadline. It is also given that every job takes single unit of time, so the minimum possible deadline for any job is 1. Maximize total profit if only one job can be scheduled at a time.

  28. Job Sequencing Problem • Problem Input: • Job ID, Deadline, Profit • Problem Output: • maximum profit sequence of jobs • Logic: • Apply greedy algorithm • Overload the operators wherever possible

  29. Algorithm 1) Sort all jobs in decreasing order of profit. 2) Initialize the result sequence as first job in sorted jobs. 3) Do following for remaining n-1 jobs • If the current job can fit in the current result sequence without missing the deadline, add current job to the result. • Else ignore the current job.

  30. Operator Overloading in Railway Reservation Problem

More Related