An exercise am working on, I created two classes, Book & Date. The Date constructor simply takes 3 int arguments for day, month and year. The Book constructor takes string isbn, string title, string author, Date copyright_date.
I thought i could use the Date constructor to create a Date object inside the Book constructor but it doesnt seem to be working.
#include <bits/stdc++.h>
using namespace std;
class Date{
public:
class Invalid{};//to throw in error
Date(int d,int m,int y);
Date() = default;
//getters
int get_day(){return day;};
int get_month(){return month;};
int get_year(){return year;};
//helper functions
private:
int day{1};
int month{1};
int year{2024};
bool is_valid();
};
Date::Date(int d,int m,int y):day{d},month{m},year{y}
{
if(!is_valid()) throw Date::Invalid{};
}
bool Date::is_valid(){
return(month<1||12<month)? false: true;
}
ostream& operator << (ostream& os, Date d){ //operator overload to display Date objects
return os<<d.get_day()<<'-'<<d.get_month()<<'-'<<d.get_year()<<endl;
}
class Book{
public:
//constructors
Book():ISBN("xxx-xx-x"),title("title"),author("Aloy"),copyright_date(Date() ) {}//default constructor
Book(string isbn,string t,string a,Date c):ISBN(isbn),title(t),author(a),copyright_date(c) {}
//getters
string get_ISBN(){ return ISBN; }
string get_title(){ return title; }
string get_author(){ return author; }
Date get_copyright_date(){ return copyright_date; }
void print_info(){ cout<<"Book title: "<<title<<"nAuthor: "<<author<<"nISBN: "<<ISBN<<"nCopyright date: "<<copyright_date<<"Status: "<< ((is_checked_out)? "Checked out":"Available")<<endl; }
//setters
void set_ISBN(string i){ ISBN=i; }
void set_title(string t){ title=t; }
void set_author(string a){ author=a; }
void set_copyright_date(Date d){ copyright_date=d; }
void check_in(){ is_checked_out = false; }
void check_out(){ is_checked_out = true; }
void check(){ (is_checked_out)? cout<<"Out"<<endl : cout<<"Available"<<endl; }
private:
string ISBN;
string title;
string author;
Date copyright_date;
bool is_checked_out{false};
};
bool operator==(Book& b1, Book& b2){
return b1.get_ISBN()==b2.get_ISBN();
}
int main()
{
Book book1{"233-725-C2","Shadow of Mordor","J.R.R.Tolkien",Date dd(14,7,1954)};
book1.print_info();
return 0;
}
2