I don\'t know how to start this. Create a class called MyInteger. It should have
ID: 3668643 • Letter: I
Question
I don't know how to start this.
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.
If you have the following code in your main method:
The output should be:
The files must be named MyInteger.hpp and MyInteger.cpp.
Explanation / Answer
MyInteger.hpp
#ifndef MYINTEGER_HPP
#define MYINTEGER_HPP
class MyInteger
{
private:
int *pInteger;
public:
void setMyInt(int);
int getMyInt() const;
MyInteger operator=(const MyInteger &);
MyInteger(const MyInteger &);
MyInteger(int inNum)
{
pInteger = new int;
setMyInt(inNum);
}
~MyInteger()
{
delete pInteger;
}
};
#endif
MyInteger.cpp
#include "MyInteger.hpp"
MyInteger::MyInteger(const MyInteger &obj)
{
pInteger = new int;
*pInteger = *obj.pInteger;
}
MyInteger MyInteger::operator=(const MyInteger &right)
{
delete pInteger;
pInteger = new int;
*pInteger = *right.pInteger;
return *this;
}
void MyInteger::setMyInt(int intIn)
{
*pInteger = intIn;
}
int MyInteger::getMyInt() const
{
return *pInteger;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.