Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++ Create a class called MyInteger. It should have a field of type pointer-t

ID: 3668664 • Letter: I

Question

In C++

Create a class called MyInteger. It should have a field of type pointer-to-int called pInteger. It should have a constructor that takes as a parameter an int - the constructor will then dynamically allocate memory for an int, using pInteger, and assign the parameter's value to that memory. The class should have a destructor that will deallocate that memory when the object is destroyed. You should write a copy constructor that will correctly make a separate copy of the memory pInteger points to, and make pInteger in the new object point to it (pp. 715-720). You should overload the = operator such that each of the two objects involved has its own separate copy of the memory that its own pInteger points to. The =operator should have a return type of MyInteger. There should be methods called setMyInt and getMyInt for getting and setting the value of the int that pInteger points to.

Explanation / Answer

#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
class MyInteger
{
int *Pinteger;

public:

MyInteger(int n)            //parametrised constructor
{
Pinteger=new int();
*Pinteger=n;
}

~MyInteger()             //destructor
{
delete Pinteger;
}

MyInteger(const MyInteger &obj)         //Destructor
{
Pinteger=new int();
*Pinteger=*obj.Pinteger;   
}

int getMyInt()
{
    return *Pinteger;
}

void setMyInt(int n)
{
    *Pinteger=n;
}


MyInteger operator=(const MyInteger &D )
      {
      Pinteger=D.Pinteger;
      return *Pinteger;
      }



};


int main()
{

return 0;
}