So I am fairly new to coding in C++ and in my current programming course we are learning about operator overloading and friend functions. We were told to make a class Money that has different types of constructors and overloaded operators. The program was much easier when we didn't have pointers for our private member variables, but now it's a little over my head.
I wanted to get some help on this before I continued on defining the rest of the overloaded operator functions. Basically what I'm trying to do is add two objects of the Money class together, but I keep on getting a segmentation fault when I run the program. I know this has to do with pointers and accessing memory that can't be accessed, but I'm not sure where I went wrong.
It's a short program so far, so the code should be easy to read. Any help would be appreciated!
class Money
{
public:
Money(int d=0, int c=0);
Money(const Money&);
// ~Money();
Money& operator=(const Money&);
Money operator+(const Money&) const;
Money operator-(const Money&) const;
Money& operator*(double);
Money& operator/(double);
friend istream& operator>>(istream&, Money&);
friend ostream& operator<<(ostream&, const Money&);
private:
int* dollars;
int* cents;
};
int main()
{
Money m1(3, 43), m2(4, 64);
Money m3 = m1 + m2;
return 0;
}
Money::Money(int d, int c)
{
*dollars = d;
*cents = c;
}
Money Money::operator+(const Money& m1) const
{
Money result;
*result.dollars = *this->dollars + *m1.dollars;
*result.cents = *this->cents + *m1.cents;
return result;
}