I have a normal class called BaseView with a virtual method DisplayView. This method calls GetHeader and GetBody virtual methods to get contents for the page. I would then create a class that inherits from BaseView and override the methods that needs to display content differently than the way the base class does it.
My issue is that, although this works great, when running a code analysis I’m warned not to call the virtual functions directly.
Should I create another class layer on top of the base class that override the virtual functions and only inherit from that?
What are the disadvantages of using the virtual methods directly?
EDIT: the warning is:
CA2214 : Microsoft.Usage : xxx contains a call chain that results in a
call to a virtual method defined by the class. Review the following
call stack for unintended consequences
I think the issue is that
DisplayViewis virtual, and it’s calling virtual methods. In most cases virtual methods are called by final methods as a means of changing behaviour, for example in the strategy pattern. If a final method calls a virtual method, the compiler knows that the virtual method will always be called in all deriving classes, and therefore it is valid for the virtual method to exist.The fact that you’re calling virtual from virtual means that your design can be called into question: if
DisplayViewis virtual, another implementation may override it. The current implementation calls the virtualGetHeaderbut a deriving class may not. Therefore it cannot guarantee thatGetHeaderis not dead code.This is probably what FxCop is drawing your attention to. It wants to know that if you define a virtual method (
GetHeaderin this case) in a base class that all deriving implementations will use it.I would focus on making
DisplayViewfinal, or appraise your design in that light.