Create a class called Date that includes three pieces of information as data members-a month, a day and a year. - C++ Class

C++ examples for Class:Class Creation

Description

Create a class called Date that includes three pieces of information as data members-a month, a day and a year.

Demo Code

                  
#include <iostream>
                  //from w w w. j  av a  2s  . c o  m
class Date {
 private:
    int month = 1;
    int day = 1;
    int year = 1900;
                  
 public:
    Date(int, int, int);
                  
    // SETTERS
    void setMonth(int);
    void setDay(int);
    void setYear(int);
                  
    // GETTERS
    int getMonth();
    int getDay();
    int getYear();
                  
    void displayDate();
};
Date::Date(int m, int d, int y) {
    setMonth(m);
    setDay(d);
    setYear(y);
}
// SETTERS
void Date::setMonth(int m) { month = (m > 0 && m <= 12) ? m : 1; }
void Date::setDay(int d) { day = d; }
void Date::setYear(int y) { year = y; }
// GETTERS
int Date::getMonth() { return month; }
int Date::getDay() { return day; }
int Date::getYear() { return year; }
// prints the date mm/dd/yyyy
void Date::displayDate() {
    std::cout << getMonth() << "/" << getDay() << "/" << getYear() << std::endl;
}
                  
                  
int main(int argc, const char *argv[]) {
    Date date1(12, 7, 2020);
    Date date2(14, 23, 1255);
                  
    date1.displayDate();
    date2.displayDate();
                  
    return 0;
}

Result


Related Tutorials