what is the best design practice for this situation?
-----
Create a class or set of classes in C++ to represent the birds
Create an instance of each type of bird and add them all into a single vector
Have each bird hop and then fly in turn
Don't have a bird perform a movement that it can't perform.
Penguin:
hopping: moves 2 ft
flying: can't fly
Hawk:
hopping: can't hop
flying: moves 100 ft;

Robin:
hopping: moves 1 ft;
flying: moves 20 ft;
-----
*** This is NOT a homework question. Just curious...

Thanks

Recommended Answers

All 5 Replies

Seems like a homework problem to me. But you need to use the following :
1) Polymorphism
2) Classes
3) std::vector
4) virtual functions
5) Inheritance

No, Not a homework problem. I was asked this question in an interview. I was not sure if there is any clever way for "Don't have a bird perform a movement that it can't perform". If I define fly() and hop() both in base, how to prevent hawk from fly?
I understand the general concepts (polymorphism etc) involved in this problem

Thanks

>>Don't have a bird perform a movement that it can't perform

Can you explain this a little. Does he want a compile error? Does he wants to return
error, exceptions? Display error message?

No explanation was given, it was a written exam. I was asked to come up with the best design for this. There are only 2 functions fly and hop.
With the time allocated (there were other questions), I can only think of 2 ways.
In the derived class for penguin, do nothing in fly. In the derived class for hawk, do nothing for hop.
In the main program,
1) using base class pointer, just call both functions for each object. The dummy functions will do nothing. (doesn't exactly meet the requirement)
2)iterate through vector, check the type and call only valid function for each type. Kind of beats the purpose...

Somehow have a feeling, there is a better way out there!!!

Thanks

The way you did it is fine, you can also use aggregation if you want. Each have their
flexibility. Having a do nothing function is fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.