Migrating from C to C++ (3)

howtoprogram

https://www.youtube.com/watch?v=tj8BoOYvo00

How to Code Like Bjarne Stroustrup? I don’t know, but, one thing to do is read Bjarne Stroustrup’s C++ Style and Technique FAQ carefully.

One example from the qeustion, Why do my compiles take so long? is:

class Shape {
public:		// interface to users of Shapes
	virtual void draw() const = 0;
	virtual void rotate(int degrees) = 0;
	virtual Point center() const = 0;
	// ...
	// no data
};

struct Common {
	Color col;
	// ...
};

class Circle : public Shape, protected Common {
public:	
	void draw() const;
	void rotate(int) { } // nothing to do to rotate a circle!
	Point center() const { return cent; }
	// ...
protected:
	Point cent;
	int radius;
};

class Triangle : public Shape, protected Common {
public:	
	void draw() const;
	void rotate(int);
	Point center() const;
	// ...
protected:
	Point a, b, c;
};	

This code is given as an answer to the related question:

But what if there really is some information that is common to all derived classes (or simply to several derived classes)?

He says: Simply make that information a class and derive the implementation classes from that also.

So in my case, it could be something like this:

class Sound { // an abstract class
public:
	virtual void draw_waveform () const = 0; // a pure virtual function
	virtual void draw_waterfall() const = 0; // a pure virtual function
	// ...
};

struct AlsaParams { // Advanced Linux Sound Architecture
	snd_pcm_uframes_t   buffer_size = 0;
	snd_pcm_uframes_t   period_size = 0;
	snd_pcm_sframes_t   avail = 0;
	snd_pcm_sframes_t   frames_actually_read = 0;
	snd_pcm_t           *handle = nullptr;
	snd_pcm_hw_params_t *hwparams = nullptr;
	snd_pcm_sw_params_t *swparams = nullptr;
	snd_async_handler_t *ahandler = nullptr;
	// ...
};

class SoundIC7410 : public Sound, protected AlsaParams {
public:	
	void draw_waveform () const;
	void draw_waterfall() const;
	// ...
private:
	int nchannels = 1;
	// ...
};

class SoundSoft66 : public Sound, protected AlsaParams {
public:	
	void draw_waveform () const;
	void draw_waterfall() const;
	// ...
private:
	int nchannels = 2;
	// ...
};

void f(const vector<Sound*>& s) {
	for(auto x : s) {
		x->draw_waveform ();
		x->draw_waterfall();
	}

Selection_025

Leave a Reply

Your email address will not be published. Required fields are marked *