I have the following exercise:
Add code to make it run properly.
class MyInt
{
public:
private:
int* MyValue;
}
int main(int argc,char** a
I'm not really sure why you want to store a pointer to an int
inside a class, rather than just storing the value directly (and not have a pointer be the input to the constructor), but assuming you do actually want that, here's how you'd do it:
MyInt(int x):MyValue(new int(x)){}
But this is really, really terrible style, and you have to have a good reason for doing it. You also need to remember to free the pointer at class destruction:
~MyInt(){delete MyValue;}
I don't see anything in your original problem statement that requires the pointer to be initialized to the address of an int
. The minimal code required to fix the example would be to add a constructor that takes an int
, and initialize MyValue
to nullptr
.
class MyInt
{
public:
MyInt(int) {}
private:
int* MyValue = nullptr;
};
int main(int argc,char** argv)
{
MyInt x(1);
return 0;
}
If your compiler doesn't support C++11 then
class MyInt
{
public:
MyInt(int) : MyValue(NULL) {}
private:
int* MyValue;
};
Another way:
MyInt(int x) : MyValue(new int(x)) {}
This doesn't require the additional member. However, you have to make sure that you deallocate the memory in the destructor.
~MyInt() { delete MyValue; }