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
- Using the fruit struct example, create a function that takes a fruit object and prints its name. Show how a string can be automatically cast to a fruit object when passed to the function. Then, modify the fruit struct to use the explicit keyword and show how to explicitly create fruit objects to pass to the function.
#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;
}