Re: Design problem in C++
dragoncoder <pktiwary@gmail.com> wrote:
Hello experts,
This is actually a design problem which I want to solve using c++.
I have the following class.
class Animal
{
public:
virtual void run() { uselegs(); }
private:
void uselegs() { // Use 4 legs }
};
And I have the following animals
class Dog: public Animal
{
};
class Cat: public Animal
{
};
class Cow: public Animal
{
};
Now One more animal comes.
class Man: public Animal
{
};
But Man has only 2 legs so it can not "Use 4 legs".
I understand that in this case Man *_is_not_* an animal but except
this "Use 4 legs" property everything is same. My question is how can
I reuse my existing Animal class so that Man can use 2 legs to walk,
with the least change in the code and not making the design bad.
Please help.
Thanks in advance.
The correct answer is probably to redesign the classes somewhat:
// is 'interface'
class Runner {
public:
virtual void run() = 0;
};
class FourLeggedAnimal : public Runner {
public:
void run() { run_with_four_legs(); } // compiler uninlines
private:
void run_with_four_legs();
};
/* classes Cat, Dog, Emu, etc. */
class Man : public Runner {
public:
void run() { run_like_forrest(); } // compilier uninlines
private:
void run_like_forrest();
};
This could, of course, shatter things because the interfaces and class
signatures change. You might not have the luxury of redesigning the
parent class.
A *pragmatic* answer, not as correct as actually fixing things to
correctly incorporate your desired change, is to simply override run()
in Man (that's why it's virtual). I'd probably also put a note on it
saying 'FIX THIS' or 'REVIEW THIS'.
This doesn't break current interfaces or class signatures. It may also
be code that ranges in naughtiness from 'mild' to 'Catholic schoolgirl
nympho', depending on the real context. (I'm assuming this is a
simplified version of a RL problem, rather than homework.)
Keith
--
Keith Davies "Sometimes my brain is a very strange
keith.davies@kjdavies.org to live in."
keith.davies@gmail.com -- Dana Smith
http://www.kjdavies.org/