I am trying to write a program that overloads the operator. When I input 7 and 3, it correctly prints: First vacation: Days: 7, People: 3 But incorrectly prints: Second vacation: Days: -158458720, People: 32764 It should be outputting: Second vacation: Days: 12, People: 3
#include <iostream>
using namespace std;
class FamilyVacation {
public:
void SetNumDays(int dayCount);
void SetNumPeople(int peopleCount);
void Print() const;
FamilyVacation operator (int moreDays);
private:
int numDays;
int numPeople;
};
void FamilyVacation::SetNumDays(int dayCount) {
numDays = dayCount;
}
void FamilyVacation::SetNumPeople(int peopleCount) {
numPeople = peopleCount;
}
// FIXME: Overload operator so can write newVacation = oldVacation 5,
// which adds 5 to numDays, while just copying numPeople.
FamilyVacation FamilyVacation::operator (int moreDays) {
numDays = moreDays 5;
}
void FamilyVacation::Print() const {
cout << "Days: " << numDays << ", People: " << numPeople << endl;
}
int main() {
FamilyVacation firstVacation;
FamilyVacation secondVacation;
int userDays;
int userPeople;
cin >> userDays;
cin >> userPeople;
cout << "First vacation: ";
firstVacation.SetNumDays(userDays);
firstVacation.SetNumPeople(userPeople);
firstVacation.Print();
cout << "Second vacation: ";
secondVacation = firstVacation 5;
secondVacation.Print();
return 0;
}
CodePudding user response:
Your operator has undefined behavior.
It is declared as returning a new FamilyVacation
object, but is actually not returning anything at all. That is why secondVacation.Print()
is printing garbage.
Worse, your operator is modifying the object it is being called on (and not even modifying it with the correct value!), which is the wrong behavior for this operator to implement. See What are the basic rules and idioms for operator overloading?
Try this instead:
FamilyVacation FamilyVacation::operator (int moreDays)
{
FamilyVacation ret;
ret.SetNumDays(numDays moreDays);
ret.SetNumPeople(numPeople);
return ret;
}