Reputation: 11
I'm learning C++ in school and when talking about the Observer pattern, my prof says that the Subject should be Abstract at all costs. If there are no obvious PV methods make the destructor PV. They also said that you still need to implement the base class destructor to avoid problems. So 2 follow up questions:
Upvotes: 1
Views: 521
Reputation: 275330
I use the observer pattern with concrete subjects all of the time. I have polymorphic observers, but use type erasure rather than inheritance for polymorphism.
As a general rule, abstract interfaces should have virtual or protected destructors. Otherwise deleting through it can happen accidentally and cause UB. If you use type erased destruction (like shared ptr) this requirement goes away; it is a quirk of delete based destruction.
Basically your teacher is teaching 90s C++, where those rules would be hard to avoid. It isn't a horrible approach, and is probably what your professor is familiar with. The alternatives require skills and knowledge you probably lack, and can be dangerous if done wrong.
template<class...Args>
struct broadcaster {
std::shared_ptr<void> listen( std::function<void(Args...)> );
void operator()( Args... ) const;
};
this, with details removed for simplicity, is a concrete subject that uses value based polymorphic listeners; it violates everything your professor has stated must happen.
I wouldn't teach this to first year students however.
Upvotes: 0
Reputation: 62563
If you make destructor a pure virtual function, you still have to provide implementation for it. The reason for that is that destructors of all classes in inheritance chain are called, so implementation must be provided.
As for the insistence on subject being abstract in general, I am not quite sure why it is so important. I do not necessarily agree with that.
Upvotes: 3