Call base function then inherited function

前端 未结 6 1202
野性不改
野性不改 2020-12-01 02:48

I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the ba

6条回答
  •  离开以前
    2020-12-01 03:10

    Not exactly. But I've done something similar using abstract methods.

    Abstract methods must be overriden by derived classes. Abstract procs are virtual so you can be sure that when the base class calls them the derived class's version is called. Then have your base class's "Must Run Code" call the abstract proc after running. voila, your base class's code always runs first (make sure the base class proc is no longer virtual) followed by your derived class's code.

    class myBase
    {
        public /* virtual */ myFunction()  // remove virtual as we always want base class's function called here 
        { /* must-run code, Called first */ 
    
            // call derived object's code
            myDerivedMustcallFunction();    
        }
    
        public abstract myDerivedMustCallFunction() { /* abstract functions are blank */ }
    }
    
    class myInherited : myBase
    {
        public override myDerivedMustCallFunction()
        { /* code to be run in derived class here */ }
    }
    

提交回复
热议问题