Refactored to avoid memory leaks. Added common class Bar for inheritance.