So I have just been teaching myself C++ for a while now and I seem to have found myself stuck in a rut of code so to say. What I need help under standing is what the purpose is, and how the "&" in the open parenthesis affects what this here snippet of code does. Whenever I see it my brain just assumes address of. Thanks in advance fellow humans, sorry for anything that may have slipped my mind and made my question unclear.
booloperator == (const ClassType& compareTo)
{
//comparison code here, return true if equal else false.
}
//actual app
#include <iostream>
class Date
{
private:
int Day, Month, Year;
public:
//Constructor that initializes the object to a day, month and year
Date(int InputDay, int InputMonth, int InputYear)
: Day(InputDay), Month(InputMonth), Year(InputYear) {};
booloperator == (const Date& compareTo)
{
return((Day == compareTo.Day)
&& (Month == compareTo.Month)
&& (Year == compareTo.Year));
}
booloperator != (const Date &compareTo)
{
return !(this->operator==(compareTo));
}
void DisplayDate()
{
std::cout << Day << " / " << Month << " / " << Year << std::endl;
}
};
int main()
{
Date Holiday1 (25,12,2011);
Date Holiday2 (31,12,2011);
std::cout << "Holiday 1 is: ";
Holiday1.DisplayDate();
std::cout << "Holiday 2 is: ";
Holiday2.DisplayDate();
if(Holiday1 == Holiday2)
{
std::cout << "Equality operator: The two are on the same day" << std::endl;
}
else
{
std::cout << "Equality operator: The two are on diffrent days" << std::endl;
}
if(Holiday1 != Holiday2)
{
std::cout << "Inequality operator: The two are on diffrent days" << std::endl;
}
else
{
std::cout << "Inequality operator: The two are on the smae day" << std::endl;
}
return 0;
}
Edit: On a side note whether it's there or not it seems to compile in my program just fine as well as run.
What I need help under standing is what the purpose is, and how the "&" in the open parenthesis affects what this here snippet of code does
For user defined types, it's always better to pass it by reference to const instead of by copy, like :
booloperator ( Date compareTo ) { } // pass a Date by copy (slow)
Since with the above code, you are copying a whole Date object every time you call that function
and that may slow down ur program.
If you pass by reference it will only copy a reference to the object passed to the function
(it's something like a pointer, i dont know the details) and it takes only a few bytes