Question #72131

Create a class named MusicalComposition that contains fields for title, composer, and year written. Include a constructor that requires all three values and an appropriate display function. The child class NationalAnthem contains an additional field that holds the name of the anthem’s nation. The child class constructor requires a value for this additional field. The child class also contains a display function. Write a main()function that instantiates objects of each class and demonstrates that the functions work correctly. Save the file as Compositions.cpp.

Expert's answer

#include <iostream>
#include <string>
using namespace std;
class MusicalComposition
{
protected:
string my_title;
string my_composer;
int my_year;

public:
MusicalComposition(string title, string composer, int year);
virtual void display();
};
MusicalComposition::MusicalComposition(string title, string composer, int year)
{
my_title = title;
my_composer = composer;
my_year = year;
}
void MusicalComposition::display()
{
cout<<"\nIn base class\n\n"<<endl;
cout << "Title: " << my_title << endl;
cout << "Composer: " << my_composer<<endl;
cout << "Year: " << my_year << endl;
}
class NationalAnthem : public MusicalComposition
{
string my_nation;

public:
NationalAnthem(string title, string composer, int year, string nation) : MusicalComposition(title, composer, year)
{
my_nation = nation;
}
void display();
};

void NationalAnthem::display()
{
cout<<"\nIn derived class\n\n"<<endl;
cout << "Title: " << my_title << endl;
cout << "Composer: " << my_composer<<endl;
cout << "Year: " << my_year << endl;
cout << "Nation: " << my_nation << endl;
}
int main()
{
MusicalComposition sonata_14("Moonlight", "Ludvig van Beethoven", 1801);
NationalAnthem anthem("Ще не вмерла Украiни", "P. Verbitskiy", 1863, "Ukraine");

sonata_14.display();

anthem.display();

return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS