C++: Operator Overloading, example using “-” for birthday

Date.cpp

#include <iostream>
#include <conio.h>
//using namespace std;

class Date
{
private:
   int month;
   int year;
   int day;
public:

    Date()          //constructor1
    {
        month=0;
        day=0;
        year=0;
    }

    Date(int m, int d, int y)       //constructor2
    {
        month = m;
        day = d;
        year = y;
    }

    void getdata()
    {
        std::cout<<"Enter month, day and year respectively: ";
        std::cin>>month>>day>>year;
    }

    void display()
    {
        std::cout<<"Month : "<<month<<std::endl;
        std::cout<<"Day : "<<day<<std::endl;
        std::cout<<"Year : "<<year<<std::endl;
    }

    //Operator declaration in Class
    friend Date operator - (Date &ob1, Date &ob2)
    {
        Date temp;
        temp.year = ob1.year - ob2.year;
        temp.month = ob1.month - ob2.month;
        temp.day = ob1.month - ob2.month;

        //same month as current day, but different days
        if(temp.month == 0)
        {
            if(temp.day > 0)
                temp.year--;
        }
        else if(temp.month < 0)
        {
            temp.year--;
        }
        return(temp);
    }

    int getAge(){
        return year;
    }

};

DateDriver.cpp

#include "distance.cpp"
#include <iostream>
#include <conio.h>
#include "Date.cpp"
#include <ctime>

using namespace std;
/*
DateDriver.cpp

compute age from your DOB

*/
int main()
{
//  clrscr();
    Date Birthdate;

    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );

    //set current date automatically
    Date currentDate(now->tm_mon+1, now->tm_mday, now->tm_year+1900);
    Date year;

    cout<<"\n=====Enter Data for OBJECT1=====\n";
    Birthdate.getdata();

    //operator overload
    year = currentDate - Birthdate;

    cout << "Your age is: " << year.getAge();


    return 1;

}

Output:
output

Leave a Reply