카테고리 없음

Exercise 15.1: Inheritance, Polymorphism, and Virtual Functions

07514673 2021. 12. 20. 14:54

Exercise 15.1: Inheritance, Polymorphism, and Virtual Functions

Here is the problem specification:

Create a base class named Book. Data fields include title and author; functions include those that can set and display the fields.

Derive two classes from the Book class: Fiction, which also contains a numeric grade reading level, and NonFiction, which contains a variable to hold the number of pages.

The functions that set and display data field values for the subclasses should call the appropriate parent class functions to set and display the common fields, and include specific code pertaining to the new subclass fields.

Write a test program that demonstrates the use of the classes and their functions.

Sample Run

Book is Scarlet Letter by Hawthorne
Reading level is 10
Book is Log Cabin Building by Landers
328 pages

 

#include <iostream>
#include <string>
using namespace std;
class book {
public:
    void setTitle(string t);
    void setAuthor(string a);
    string const getTitle();
    string const getAuthor();
    book(string t, string a);
    void printInfo();
private:
    string title;
    string author;
};
void book::setTitle(string t) {
    title = t;
}
void book::setAuthor(string a) {
    author = a;
}
void book::printInfo() {
    cout << "Book is " << title << " by " << author << endl;
}
 string const book::getTitle() {
    return title;
}
 string const book::getAuthor() {
    return author;
}
book::book(string t, string a) {
    title = t;
    author = a;
}
class Fiction: public book{
public:
    int const getGradeReadingLevel();
    void setGradeReadingLevel(int g);
    void printInfo();
    Fiction(string t, string a, int g);
private:
    int gradeReadingLevel;
};
    int const Fiction::getGradeReadingLevel() {
    return gradeReadingLevel;
}
void Fiction::setGradeReadingLevel(int g) {
    gradeReadingLevel = g;
}
void Fiction::printInfo() {
    book::printInfo();
    cout << "Reading level is " << gradeReadingLevel << endl;
}
Fiction::Fiction(string t, string a, int g) :book(t, a) {
    gradeReadingLevel = g;
}
class NonFiction : public book {
public:
    void setNumPages(int n);
     int const getNumPages();
    void printInfo();
    NonFiction(string t, string a, int n);
private:
    int numPages;
};
void NonFiction::setNumPages(int n) {
    numPages = n;
}
 int const NonFiction::getNumPages() {
    return numPages;
}
void NonFiction::printInfo() {
    book::printInfo();
    cout << numPages << " pages" << endl;
}
NonFiction::NonFiction(string t, string a, int n) :book(t,a) {
    numPages = n;
}
int main(){
{
    Fiction book1("Scarlet Letter", "Hawthorne", 10);
    NonFiction book2("Log Cabin Building", "Landers", 328);
    book1.printInfo();
    book2.printInfo();
}
    return 0;
}