-
Sharing Class functions
Hello there, it's been a while since I posted so it's nice to see you guys again! :)
Straight to the point... I have a class which has a certain function, but I need that function to be used by another class. I made some research and the best solution might be using a "friend function". Is it the best way to do so? Can anyone shed some light on this topic for a better understanding? Thanks in advance.
Code:
class Playlist
{
public:
Playlist();
// "set" methods
void setMusicList(const std::string& filename);
// "get" methods
std::vector<uint> getMusicList() const {return musicList;};
// other
void addSongToPlaylist(uint songID);
void removeSongFromPlaylist(uint songID);
void showPlaylist() const; -> Function which needs to be used by a RadioStation (class) function
void orderPlaylist();
void writePlaylistToFile(const std::string& filename);
private:
std::vector<uint> musicList;
// these methods can be private, the function orderPlaylist calls them
void swapElementsInPlaylist();
bool isOrdered() const;
};
class RadioStation
{
public:
RadioStation(); // creates a radio station
// "set" methods
void setName(const std::string& n) {name = n;};
void setTracksToBroadcast();
void setTopTracks();
void setUsers();
// "get" methods
std::string getName() const {return name;};
Playlist getTTBroadcast() const {return tracksToBroadcast;};
Playlist getTopTracks() const {return topTracks;};
std::vector<User> getUsers() const {return radioUsers;};
// other
void addUser(User u); // adds a new listener to a previously created r station
void createTopTenFile();
void showTopTracks() const; // show top ten tracks
void createNewUser();
// radio station menus
void firstLaunch();
void userAccount(const std::string& lineWithUserInfo);
void userOptions(); -> Function which requires the "showPlaylist" function
void login();
void signup();
void mainMenu();
private:
std::string name;
Playlist tracksToBroadcast;
Playlist topTracks;
std::vector<User> radioUsers;
};
-
I cannot see the problem. showPlaylist() is a public function of Playlist().
RadioStation has two Playlist members tracksToBroadcast and topTracks
so it is ok in RadioStation::userOptions() to call
Code:
topTracks.showPlaylist();
or
Code:
tracksToBroadcast.showPlaylist();
no friend needed
Kurt
-
Friends are for making private or protected data/functions available to specific outside functions/classes/structs. As your function is public, you don't need that.