Song struct

Song struct

Define a Song struct with member variables title, artist, and length. Add two constructors: one that takes parameters for title, artist, and length, and a default constructor that sets these values to default strings and a length of 0. Create instances of Song using both constructors and print the details.

Example output:

Song 1 Details:
Title: Bohemian Rhapsody
Artist: Queen
Length: 354 seconds

Song 2 Details:
Title: Unknown Title
Artist: Unknown Artist
Length: 0 seconds

Answer

#include <iostream>
#include <string>

struct Song {
    std::string title;
    std::string artist;
    int length;

    // Constructor with parameters
    Song(const std::string& t, const std::string& a, int l) {
        title = t;
        artist = a;
        length = l;
    }

    // Default constructor
    Song() {
        title = "Unknown Title";
        artist = "Unknown Artist";
        length = 0;
    }

    void display_info() const {
        std::cout << "Title: " << title << std::endl;
        std::cout << "Artist: " << artist << std::endl;
        std::cout << "Length: " << length << " seconds" << std::endl;
    }
};

int main() {
    // Using parameterized constructor
    Song song1("Bohemian Rhapsody", "Queen", 354);
  
    // Using default constructor
    Song song2;

    std::cout << "Song 1 Details:" << std::endl;
    song1.display_info();
    std::cout << std::endl;

    std::cout << "Song 2 Details:" << std::endl;
    song2.display_info();

    return 0;
}
Questions