C++ examples for Class:Class Creation
Defines a Date class that includes a constructor, a mutator, and an accessor as well as the two functions.
#include <iostream> #include <iomanip> // needed for formatting using namespace std; // declaration section class Date { private: int month; int day; int year; public: Date(int mm = 1, int dd = 1, int yyyy = 2014) // inline constructor {month = mm; day = dd; year = yyyy;} void setDate(int mm, int dd, int yy) // inline mutator {month = mm; day = dd; year = yy;} void showDate(); // accessor bool isLeapYear(); bool operator==(const Date&); }; // implementation section void Date::showDate() { //show year in last two digits cout << "The date is " << setfill('0') << setw(2) << month << '/' << setw(2) << day << '/' << setw(2) << year % 100; cout << endl; } bool Date::isLeapYear() { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) return true; // is a leap year else return false; // is not a leap year } bool Date::operator==(const Date& date2) { if (day == date2.day && month == date2.month && year == date2.year) return true; else return false; }