Using C++ implement class with dynamic memory allocation using new and delete operator to overload

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJfShSmc4uzJ32B_Cnh6KDE7EeSGsUpqwnmXpsZMSrMSp0wjgo7gGWZu_JIDHC_zUiWwWkPBhm3Pz_vS0k-tjHPGbd4J7sxNkEVv5q-YbMtId0PtXLQqi2n_k4Dee10jKN6F-IOkz4Wqgg/s1600/c+and+c%252B%252B+meansofmine.jpg



Overload the new and delete operators to provide custom dynamic allocation of memory.
Aim
To implement class with dynamic memory allocation using new and delete operator to overload.

Algorithm

Step 1: Start the Program Execution
Step 2: Create the Classes and declare all the Variables and Member functions.
Step 3: Using the classes with dynamic memory alloction.
Step 4: New and delete operator is overloaded along with dynamic
             memory allocation.
Step 5: Create the class.
Step 6: Declare the new and delete operator.
Step 7: Perform the overload operation
Step 8: Display the result.
Step 9: Stop the Program Execution.


Program:

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class vector
{
 private:
 int *array;
 public:
  void *operator new(size_t size)
  {
    void *v;
    cout<<"\n operator new invoked____________";
    v=malloc(size);
    if(!v)
    {
      cout<<"Unable to allocate memory";
      exit(0);
     }
     return v;
   }
   void operator delete(void *v)
  {
    cout<<"\n Operator delete invoked";
    free(v);
   }
    void read(int);
    int max(int);
    int sum(int);
 };
  void vector::read(int s)
  {
   for(int i=0;i<s;i++)
   {
     cout<<"\n Enter the element:"<<i+1<<":";
  
  cin>>array[i];
   }
}
 int vector::sum(int s)
 {
   int tot=0;
   for(int i=0;i<s;i++)
   tot+=array[i];
   return tot;
 }
 int vector::max(int s)
 {
   int max=0;
   for(int i=0;i<s;i++)
   if(array[i]>max)
   max=array[i];
   return max;
 }
 void main()
{
  int s;
  clrscr();
  cout<<"\n Enter how many elements";
  cin>>s;
  vector *vec=new vector;
  cout<<"\n Enter vector data_________";
  vec->read(s);
  cout<<"\nThe maximum value is_________"<<vec->max(s);
  cout<<"\n The sum is____________"<<vec->sum(s);
  delete vec;
  getch();
 }


OUTPUT:

Enter how many elements:2
Operator new overloading………………………
Enter the element1:3
Enter the element2:5
The maximum value is …………5
The sum is…………………………………8
Operator delete invoked…

1 comments:

Anonymous said...

nice

Post a Comment