Erin Edward
Erin Edward

Reputation: 11

Observer Pattern: Why should Subject be Abstract?

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:

  1. Why do we need to implement base class destructor? What problems would not doing so cause?
  2. Why is it so important Subject base class be abstract? I understand why Observer base class needs to be abstract, but why subject?

Upvotes: 1

Views: 521

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

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

SergeyA
SergeyA

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

Related Questions