https://isocpp.org/wiki/faq/virtual-functions#pure-virtual
I removed almost all of my if and/or switch statements using pure virtual functions.
/* Sound.h */ #ifndef SOUND_H_ #define SOUND_H_ #include "AlsaParams.h" #include <asoundlib.h>; class Sound : public AlsaParams { public: Sound(); virtual int get_channels () const = 0; virtual int get_nfft () const = 0; virtual int get_spectrum_x () const = 0; virtual int get_spectrum_y () const = 0; virtual int get_waterfall_x() const = 0; virtual int get_waterfall_y() const = 0; virtual int asound_fftcopy () = 0; int asound_init(); int asound_go(); int asound_read(); int asound_set_hwparams(); int asound_set_swparams(); virtual ~Sound(); private: int count = 0; }; #endif /* SOUND_H_ */
/* SoundIC7410.h */ #ifndef SOUNDIC7410_H_ #define SOUNDIC7410_H_ #include "AlsaParams.h" #include "Sound.h" class SoundIC7410: public Sound { public: SoundIC7410(char *s); int get_channels () const override { return channels; } int get_nfft () const override { return nfft; } int get_spectrum_x () const override { return 512; } int get_spectrum_y () const override { return 50; } int get_waterfall_x() const override { return 512; } int get_waterfall_y() const override { return 150; } int asound_fftcopy() override; virtual ~SoundIC7410(); }; #endif /* SOUNDIC7410_H_ */
There is now only one such statement here:
void f(Sound *s){ nch = s->get_channels(); for(int ix=0;ix<spectrum_x;ix++) { if(nch == 1) { /* IC7410 */ ixx = ix; } else if(nch == 2) { /* Soft66LC4 */ ixx = (2*nfft - (spectrum_x/2) + ix) % nfft; } // draw spectrum and waterfall here } }
The if statement is here because I wish to set the DC to the left edge or to the center depending on the signals. Of course, I can write functions for each derived class, like:
ixx= s->g(ix);
but, I do not know if I should.