Home >Backend Development >C++ >Why Should Virtual Member Calls Be Avoided in Constructors?
Avoid Virtual Member Calls in Constructors
When attempting to call a virtual member from an object's constructor, ReSharper raises a warning. Understanding why this practice should be avoided is crucial.
Construction Process
In C#, class construction involves executing initializers from most derived to base class, followed by constructor execution from base to most derived class.
Method Invocation
In .NET, objects inherit their method table from the most derived type during construction, allowing virtual method calls to target the most derived type.
Virtual Method Invocation in Constructors
If a virtual method is called within a constructor, and the object is not the most derived type, the virtual method will execute against a class with uninitialized constructors. This can result in accessing an uninitialized object, leading to potential issues.
Mitigation
If the class is marked as sealed, it ensures that it remains the most derived type. In such cases, virtual method calls from constructors are safe.
The above is the detailed content of Why Should Virtual Member Calls Be Avoided in Constructors?. For more information, please follow other related articles on the PHP Chinese website!