fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. // Base class
  6. class Media {
  7. protected:
  8. string title;
  9. double duration;
  10.  
  11. public:
  12. Media(string t, double d) : title(t), duration(d) {}
  13.  
  14. virtual void display() const {
  15. cout << "Title: " << title << "\nDuration: " << duration << " minutes" << endl;
  16. }
  17.  
  18.  
  19. };
  20.  
  21. // Subclass: Song
  22. class Song : public Media {
  23. private:
  24. string artist, genre;
  25.  
  26. public:
  27. Song(string t, double d, string a, string g)
  28. : Media(t, d), artist(a), genre(g) {}
  29.  
  30. void display() const override {
  31. Media::display();
  32. cout << "Artist: " << artist << "\nGenre: " << genre << endl;
  33. }
  34. };
  35.  
  36. // Subclass: Podcast
  37. class Podcast : public Media {
  38. private:
  39. string episode;
  40.  
  41. public:
  42. Podcast(string t, double d, string e)
  43. : Media(t, d), episode(e) {}
  44.  
  45. void display() const override {
  46. Media::display();
  47. cout << "Episode: " << episode << endl;
  48. }
  49. };
  50.  
  51. int main() {
  52. // Stack-allocated objects
  53. Song song("Imagine", 3.5, "John Lennon", "Pop");
  54. Podcast podcast("Tech Talks", 45.0, "Episode 12: AI Trends");
  55.  
  56. // Directly call display() for each object
  57. song.display();
  58. cout << "-------------------" << endl;
  59.  
  60. podcast.display();
  61. cout << "-------------------" << endl;
  62.  
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Title: Imagine
Duration: 3.5 minutes
Artist: John Lennon
Genre: Pop
-------------------
Title: Tech Talks
Duration: 45 minutes
Episode: Episode 12: AI Trends
-------------------