Reputation: 367
Ok. I have the structure:
struct birthdayPerson
{
int day, month, year;
public:
void Show()
{
std::cout << day << " " << month << " " << year << std::endl;
}
};
Then i want to overload the "==" so it can compare 2 instateated structs if those people has the same birthday (day and month). I have a 2 element array pointer of this struct:
birthdayPerson * personBirth[2];
personBirth[0] = new birthdayPerson;
personBirth[1] = new birthdayPerson;
Then i overload like this:
bool operator==(birthdayPerson person1, birthdayPerson person2)
{
return (person1.day == person2.day &&
person1.month == person2.month);
}
And finally i use in the code:
bool sameBirthDay = personBirth[0] == personBirth[1];
But, why it doesn't call the "overladed" function (operator)?. What am i doing worong?
Upvotes: 0
Views: 58
Reputation: 60238
personBirth
is an array of BirthdayPerson*
. You need to dereference pointers to compare the objects they are pointing to:
bool sameBirthDay = *personBirth[0] == *personBirth[1];
Otherwise you are comparing 2 pointers, which is not the same thing. (and also the reason it doesn't call your operator==
on birthdayPerson
).
Also, I can't see any reason why you are using pointers at all in this code. You could just create objects instead. If you want a collection of objects, use std::vector
, or if you know the number of objects you need at compile time, you can use std::array
.
This is not related to your question, but as @RemyLebeau points out in their answer, your operator==
is not idiomatic. The signature should instead be:
bool operator==(birthdayPerson const &person1, birthdayPerson const &person2);
Otherwise you are making needless copies of the objects you're comparing.
Upvotes: 3
Reputation: 597036
First off, your operator==
should take its parameters by const reference:
bool operator==(const birthdayPerson &person1, const birthdayPerson &person2)
Second, your array contains birthdayPerson*
pointers, not actual birthdayPerson
objects. Your statement personBirth[0] == personBirth[1]
is comparing pointers, which is why your operator is not invoked. You need to deference the pointers to compare the objects properly:
bool sameBirthDay = *(personBirth[0]) == *(personBirth[1]);
Otherwise, change the array to hold objects, rather than pointers to objects:
birthdayPerson personBirth[2];
...
bool sameBirthDay = personBirth[0] == personBirth[1];
Upvotes: 4
Reputation: 106
Do you initiate them ? If not it fails. You do not have a default value.
bool operator==(birthdayPerson person1, birthdayPerson person2)
{
std:: cout << person1.day <<" "<<person2.day<<"\n";
return (person1.day == person2.day &&
person1.month == person2.month);
}
if no initiated:
4196144 32766
If you compare the pointers, you dont call the overloaded function. Comparing the addresses. Again fail.
Upvotes: -2