isocpp / isocpp/CppCoreGuidelines
C.82 please recommend alternative to virtual function calls in constructor/destructor
Nobody has claimed this yet.
- Dominant language
- CSS
- Stars
- 45.3k
- Forks
- 5.6k
- PR merge metrics
- No merged PRs in 30d
Description
C.82: Don’t call virtual functions in constructors and destructors
Just to be clear up front. I understand that virtual dispatch in a constructor is not a valid "alternative" because it simply doesn't work.
The guidelines identify two cases where an call to a virtual function is acceptable
- If the function is final and therefore virtual and non-virtual dispatch will have the same effect
- If the function is explicitly qualified so it's not actually a virtual call at all
As such in the scenario where I encounter or want to write code that violates this rule I have these options:
- mark the function final
- call the function explicitly
- extract the functionality of the function into a separate non-virtual function which the virtual function calls
My question is which is the preferred solution?
That's the question. My proposed answer is to combine 1 and 2 so that it's obvious to anyone reading the calling code and anyone hoping to override the function what is going on. If the function can't be final because it's overridden later then my instinct is to use 3. However I think 1 is usually a valid option because the average inheritance heirarchy isn't very deep in my experience (often just a interface with a handful of concrete implementations).
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked C.82 guideline and review the three alternatives described in the issue. Determine which option should be preferred, including when a function cannot be marked final, and document a clear recommendation; completion requires agreement on the guidance and an update to C.82.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100