I am trying to understand operating overloading a bit better and I have 2 questions.
1)Why do we need a return of Date& in this part that is by the book?
1 2 3 4 5 6
|
////Prefix++: By the book way
//Date& operator ++ ()
//{
// ++day;
// return *this;
//}
| |
I can just do it my simpler way below. I don't see a need to send my date1 object in main a reference to itself, it already is itself! But will this be a problem when other programmers look at my code and is it better to just go by the book? What do you guys see in professional programs or programs out there, all sorts of ways or mostly by the book?
1 2 3 4 5
|
//Prefix++: My simpler way
void operator ++ ()
{
++day;
}
| |
2) I am trying to understand how this is working?
1 2 3 4 5 6 7 8
|
//Postfix++
Date operator ++ (int)
{
//Date copyDate(*this);
Date copyDate(month, day, year);
++day;
return copyDate;
}
| |
From main we have:
date1++.DisplayDate(); //1/4/2000
date1.DisplayDate(); //1/5/2000
So in essence date1++ is changed to equal the "copyDate" from the postfix operator, which is another copy in memory from the original object. ++day gets incremented in the original object and not in "copyDate", which is fine. The ++day NEVER gets incremented in "copyDate" as far as I know.
But then like magic on the next line.
date1.DisplayDate();
All of a sudden "date1" is no longer equal to "copyDate" (where ++day was never incremented), but is equal to the original object as if it reverted back to the original object. So what happened?
Is it because the return of the postfix operator is by value & when the operator goes out of scope the return is destroyed & in so doing "date1" gets reverted back to the original object where ++day took place?
I know that it works, I would love to know how.
Date operator ++ (int)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
using namespace std;
class Date
{
int day;
int month;
int year;
public:
Date(int inMonth, int inDay, int inYear) : month(inMonth), day(inDay), year(inYear){}
void DisplayDate() const
{
cout << month<< "/" << day << "/" << year << endl;
}
//Prefix++: My simpler way
void operator ++ ()
{
++day;
}
////Prefix++: By the book way
//Date& operator ++ ()
//{
// ++day;
// return *this;
//}
//Postfix++
Date operator ++ (int)
{
//Date copyDate(*this);
Date copyDate(month, day, year);
++day;
return copyDate;
}
};
int main()
{
Date date1(1, 1, 2000);
date1.DisplayDate(); //1/1/2000
++date1;
date1.DisplayDate(); //1/2/2000
++date1;
date1.DisplayDate(); //1/3/2000
++date1;
date1.DisplayDate(); //1/4/2000
cout << "*****************" << endl;
date1++.DisplayDate(); //1/4/2000
date1.DisplayDate(); //1/5/2000
return 0;
}
| |