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

Create a class called MyInteger. It should have a field of type pointer-to-int c

ID: 3760314 • Letter: C

Question

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. 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.

In you have the following code in your main method:

Then the output should be :

The files must be named MyInteger.hpp and MyInteger.cpp.

Explanation / Answer

#include <iostream>

using namespace std;

class MyInteger {

private:

int *pInteger;

  

public:

MyInteger(int n) {

pInteger = new int;

*pInteger = n;

}

  

MyInteger(MyInteger &n) {

pInteger = new int;

*pInteger = n.getMyInt();

}

  

~MyInteger() {

pInteger = NULL;

delete pInteger;

}

  

  

int getMyInt() {

return *pInteger;

}

  

  

  

  

  

  

  

void setMyInt(int n) {

  

  

  

*pInteger = n;

  

  

  

}

  

  

  

void operator=(MyInteger &n) {

  

pInteger = new int;

  

*pInteger = n.getMyInt();

  

}

  

  

  

};

int main() {

  

MyInteger obj1(17);

  

MyInteger obj2 = obj1;

  

std::cout << obj1.getMyInt() << std::endl;

  

std::cout << obj2.getMyInt() << std::endl;

  

  

  

obj2.setMyInt(9);

  

std::cout << obj1.getMyInt() << std::endl;

  

std::cout << obj2.getMyInt() << std::endl;

  

  

  

MyInteger obj3(42);

  

obj2 = obj3;

  

std::cout << obj2.getMyInt() << std::endl;

  

std::cout << obj3.getMyInt() << std::endl;

  

  

  

obj3.setMyInt(1);

  

std::cout << obj2.getMyInt() << std::endl;

  

std::cout << obj3.getMyInt() << std::endl;

  

  

  

return 0;

  

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote