guys,
I have a case that needs the child class needs to call its parent virtual function at first before call its override virtual function.
BaseClass::Draw()
{
}
ChildClass::Draw()
{
BaseClass::Draw(); // BaseClass Draw must be called first.
}
GrandChildClass::Draw()
{
ChildClass::Draw(); // ChildClass Draw must be called first.
}
I want to hide this behavior from clients. Is there pattern on this?
Thanks.
For simple cases you can use a second, private member function for the overrideable behavior:
For more complex hierarchies (e.g. where you have multiple levels of inheritance), this isn’t possible since any derived class can override any virtual member function (there is no
finalin C++). Usually it is safe to assume that each derived class is doing the right thing. While I can think of a few times that I’ve run into issues because a derived class screwed up overriding, those cases were usually pretty straightforward to debug.If you are really worried about it and really want to guarantee that base-class overrides are executed first, you could use something like this, though this is quite expensive (at least this naive implementation is quite expensive):
[This is just one option; someone else can probably come up with a far more elegant solution. Personally, I’d just make sure the virtual member functions are well-documented and leave it at that.]