I am trying to learn C++ and design patterns, I am doing this by translating the Java code from this page to C++ and run it so I can learn advanced C++ syntax (at least I think so, correct me if I am wrong). I translated to code in that page, and compiled it using Digital Mars. It compiled, but when I try to run it, I get nothing. I went online and tried several online C++ compilers, it compiles but running it returns a segmentation fault errors which is to the best to my knowledge is trying to access a memory location that I am not allowed to.
I am new to C++, what did I do wrong to cause such an error.
#include <iostream>
#include <string>
using namespace std;
class MediaPlayer {
public:
virtual void play(string audioType, string fileName);
};
class AdvancedMediaPlayer {
public:
virtual void playVlc(string fileName);
virtual void playMp4(string fileName);
};
class VlcPlayer : public AdvancedMediaPlayer{
public:
void playVlc(string fileName) {
cout << "Playing vlc file. Name: "<< fileName;
}
void playMp4(string fileName);
};
class Mp4Player : public AdvancedMediaPlayer{
public:
void playVlc(string fileName);
void playMp4(string fileName) {
cout << "Playing mp4 file. Name: "<< fileName;
}
};
class MediaAdapter : public MediaPlayer {
AdvancedMediaPlayer* advancedMusicPlayer;
public:
MediaAdapter(string audioType){
if(audioType.compare("vlc")==0 ){
advancedMusicPlayer = new VlcPlayer;
}else if (audioType.compare("mp4")==0){
advancedMusicPlayer = new Mp4Player;
}
}
void play(string audioType, string fileName) {
if(audioType.compare("vlc")==0){
advancedMusicPlayer->playVlc(fileName);
}
else if(audioType.compare("mp4")==0){
advancedMusicPlayer->playMp4(fileName);
}
}
};
class AudioPlayer : public MediaPlayer {
MediaAdapter* mediaAdapter;
public:
void play(string audioType, string fileName) {
if( (audioType.compare("mp3"))==0){
cout << "Playing mp3 file. Name: " << fileName;
}
else if( (audioType.compare("vlc"))==0 || (audioType.compare("mp4"))==0){
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter->play(audioType, fileName);
}
else{
cout << "Invalid media. " << audioType << " format not supported";
}
}
};
int main() {
AudioPlayer *audioPlayer;
audioPlayer->play("mp3", "beyond the horizon.mp3");
audioPlayer->play("mp4", "alone.mp4");
audioPlayer->play("vlc", "far far away.vlc");
audioPlayer->play("avi", "mind me.avi");
}