There are a lot of mistakes in your class. It is simply not setup correctly.
The class's default constructor is not allocating the float
at all.
the class is not following the Rule of 3/5/0. It is missing a destructor to free the float, a copy constructor and copy assignment operator to make safe copies of the float, and in C++11 and later, it is missing a move constructor and move assignment operator to safely move the float between objects.
your operator+
is not dereferencing the pointer when assigning a new value to the float.
Try this instead:
class FLOAT
{
float *num;
public:
FLOAT(float f = 0) : num(new float(f)) {}
FLOAT(const FLOAT &src) : num(new float(*(src.num))) {}
// in C++11 and later...
FLOAT(FLOAT &&src) : num(src.num) { src.num = nullptr; }
// alternatively:
// FLOAT(FLOAT &&src) : num(nullptr) { std::swap(num, src.num); }
~FLOAT() { delete num; }
FLOAT& operator=(const FLOAT &rhs)
{
*num = *(rhs.num);
return *this;
}
// in C++11 and later...
FLOAT& operator=(FLOAT &&rhs)
{
std::swap(num, rhs.num);
return *this;
}
FLOAT operator+(const FLOAT& rhs)
{
FLOAT temp;
*(temp.num) = *num + rhs.getF();
return temp;
// or simply:
// return *num + rhs.getF();
}
float getF() const { return *num; }
void showF() { cout << "num : " << *num << endl; }
};
That being said, there is no good reason to dynamically allocate the float at all (except maybe as a learning experience). Let the compiler handle the memory management for you:
class FLOAT
{
float num;
public:
FLOAT(float f = 0) : num(f) {}
FLOAT(const FLOAT &src) : num(src.num) {}
FLOAT& operator=(const FLOAT &rhs)
{
num = rhs.num;
return *this;
}
FLOAT operator+(const FLOAT& rhs)
{
FLOAT temp;
temp.num = num + rhs.getF();
return temp;
// or simply:
// return num + rhs.getF();
}
float getF() const { return num; }
void showF() { cout << "num : " << num << endl; }
};
Which can then be simplified a little by letting the compiler implicitly define the copy constructor and copy assignment operator for you:
class FLOAT
{
float num;
public:
FLOAT(float f = 0) : num(f) {}
FLOAT operator+(const FLOAT& rhs)
{
FLOAT temp;
temp.num = num + rhs.getF();
return temp;
// or simply:
// return num + rhs.getF();
}
float getF() const { return num; }
void showF() { cout << "num : " << num << endl; }
};