// An example of using Inheritance, Overloading and polymorphism // This time using C++ #include #include class Book { protected: char title[30]; int npages; public: Book() { // Default constructor strcpy(title, "No title"); npages = 0; } /** A second constructor */ Book(char *booktitle, int pages) { strcpy(title, booktitle); npages = pages; } /** A public method */ virtual void Read(int pagestart, int pageend) { if (pageend < npages) { cout << "Reading " << title << " from page " << pagestart << " to " << pageend << endl; } else { cout << "Give me another book!" << endl; } } }; /** The first subclass - hardly anything extra, just to show things */ class ComicBook:public Book { public: ComicBook(char *booktitle, int pages) { strcpy(title, booktitle); /* title is not in this class - INHERITED */ npages = pages; /* likewise */ } }; class TextBook:public Book { private: char Course[10]; public: TextBook(char *booktitle, int pages, char *incourse) { Book(booktitle, pages); strcpy(Course, incourse); } void Read(int pagestart, int pageend) { cout << Course << "has a very dull textbook!" << endl; } }; //In C++, the main does not need to be in a class! int main(int argc, char **argv) { // create a new Comic Book ComicBook * favoriteComic = new ComicBook("Yukon Ho!", 85); favoriteComic->Read(75, 95); // Read is not in ComicBook, still works! // *** Inheritance *** // create a new text book, but assign it to a variable of tyep Book! // *** Polymorphism *** Book * a201Text = new TextBook("CCJ", 625, "A201"); a201Text->Read(475, 525); // This time use the overloaded Read // method in Textbook. // *** Overloading *** }