Create a base class named Book. Data fields include title and author; functions
ID: 3574743 • Letter: C
Question
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 main()function that demonstrates the use of the classes and their functions. Save the file as Books.cpp
Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
class Book
{
string title,author;
public:
void setTitle(string t)
{
title=t;
}
void setAuthor(string a)
{
author=a;
}
void displayTitle()
{
cout<<"Title is "<<title<<endl;
}
void displayAuthor()
{
cout<<"Author is "<<author<<endl;
}
};
class Fiction:public Book
{
int numGrade;
public:
void setnumGrade(int n)
{
numGrade=n;
}
void displaynumGrade()
{
cout<<"Numeric Grade is "<<numGrade<<endl;
}
};
class NonFiction:public Book
{
int numofpages;
public:
void setnumofpages(int n)
{
numofpages=n;
}
void displaynumofpages()
{
cout<<"No of pages is "<<numofpages<<endl;
}
};
int main(int argc, char const *argv[])
{
cout<<"Fiction book details ";
Fiction f;
f.setTitle("A");
f.setAuthor("B");
f.setnumGrade(5);
f.displayAuthor();
f.displayTitle();
f.displaynumGrade();
cout<<"Non Fiction book details ";
NonFiction nf;
nf.setTitle("c");
nf.setAuthor("D");
nf.setnumofpages(500);
nf.displayAuthor();
nf.displayTitle();
nf.displaynumofpages();
return 0;
}
=================================================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ book.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Fiction book details
Author is B
Title is A
Numeric Grade is 5
Non Fiction book details
Author is D
Title is c
No of pages is 500