Reputation: 25
I am having issues with trying to figure out how I would turn a data member inside a class (which was originally an int) into a pointer to a dynamically allocated piece of memory.
I know I can do int *num = new int under normal circumstances, but how would I initialize it in a class?
My teacher did an amazing job of not explaining this in the crappiest way possible in class -_-.
This is an example of the class and the constructor.
The header
class Double
{
private:
double *val;
The .cpp
Double::Double()
{
this->equals(0.0);
}
Double::Double(const Double &d)
{
this->equals(d.val);
}
Double::Double(const double &d)
{
this->equals(d);
}
Double::Double(const Interger &i)
{
this->equals(i.toInt());
}
//New overloaded constructor using strings
Double::Double(const string &s)
{
this->equals(s);
}
void Double::equals(const double &d)
{
this->val = d;
}
All I know is I have to make the data member a pointer now, but I have no idea how to create the new memory. I tried looking this up but I could not find an example of how to do DAM inside an actual class for its memory and constructor.
EDIT Solution was a simpler then I thought.
Double::Double() : val(new double) { ...... }
just have to do that to every constructor, then change any instance of d.val or this->val to *d.val or *this->val.
Upvotes: 0
Views: 1329
Reputation: 25
SOLUTION TO MY PROBLEM (So the problem is solved)
Solution was simpler then I thought.
Double::Double() : val(new double)
{
......
}
just have to do that to every constructor, then change any instance of d.val or this->val to *d.val or *this->val.
Deconstructors will have to be created to clear the memory though.
Upvotes: 1