Is this a good pattern?
BaseClass {
protected:
Data m_data;
public:
Interesting public_method() {
//returns something interesting about m_data
//what exactly depends on what the subclass put into m_data
}
}
DerivedClass {
public:
DerivedClass() { //properly populate m_data }
}
The drawback with this is that things are too “loose” and not compile-time enforced because the subclass programmer is only told to do something, not really forced to do it, so I wonder whether this is considered good practice by seasoned c++ coders.
Any good way out or better ways?
If only the superclass constructor could be forced to be called AFTER the subclass constructor did its work. Then the superclass constructor could have the required parameters in it
c++ does not allow this 🙁
The ctor-initializer-list is quite powerful. Although you can only use expressions, those expressions can include function calls. Virtually anything you can do inside the constructor body can be achieved from inside the initializer list.
Of course, you must respect construction order, so you can’t call member functions on the base class before initializing it. But you can access the base class when initializing members.