DaveHD
DaveHD

Reputation: 99

Get function that "gets" other get functions

So my challenge is: create a function that receives all of the parameters from the other get functions, like:

int get_day() const {return day;}
int get_month() const {return month;}
int get_year() const {return year;}

I want get_date() that receives all of the above gets. How can I do that? For example:

int get_date() const {
   get_day();
   get_month();
   get_year();
}

Upvotes: 1

Views: 143

Answers (3)

Simo Simov
Simo Simov

Reputation: 97

You may pack the date like this:

int get_date() const {
    return get_day() + 100 * get_month() + 10000 * get_year();
}

Note, that this is just integer, that looks like date. If you print today's date, it will be the number 20190423, which is just the number 20,190,423.

Upvotes: 2

shesharp
shesharp

Reputation: 345

you can use tm struct as in here: std::tm

std::time_t t = std::time(0);
std::tm* now = std::localtime(&t);
std::cout << (now->tm_year + 1900) << (now->tm_mon + 1) <<  (now->tm_mday);

don't reinvent the wheel

Upvotes: 1

Constantinos Glynos
Constantinos Glynos

Reputation: 3186

As I mentioned in the comments, it makes no sense to return a single int when you need your function to return 3 ints. Just return an array like this:

#include <iostream>
#include <array>

struct Cal
{
    typedef std::array<int,3> Date;

    int day = 13;
    int month = 7;
    int year = 2019;

    int getDay() const
    {
        return day;
    }
    int getMonth() const
    {
        return month;
    }
    int getYear() const
    {
        return year;
    }

    Date getDate() const
    {
        return {{getDay(),getMonth(),getYear()}};
    }
};


int main()
{
    Cal c;

    for (auto &&i : c.getDate())
        std::cout<< i <<" ";
    std::cout<<std::endl;
}

The code outputs:

13 7 2019 

Also, it's best if you simply returned the actual members instead of calling the getter functions. Besides the getDate() function is also a member of the class.

Date getDate() const
{
    return {{day,month,year}};
}

Online code example: https://rextester.com/WPXX24681

Upvotes: 1

Related Questions