Some C++ materials mention we can not call an online function inside ctor or dtor,

(
sorry ,I believe it's easier to switch to
Some C++ materials mention we'd do not to call an online function inside ctor or dtor,

)

but we might give them a call accidentally. Can there be in whatever way to avoid that?

For instance:

# include < iostream >  
using namespace std;  

class CAT  
{  
public:  
    CAT(){ f();}  
    virtual void f(){cout<<"void CAT:f()"<<std::endl;}  
};  

class SMALLCAT :public CAT  
{  
public:  
    SMALLCAT():CAT()  
    {  
    }  
    void f(){cout<<"void SMALLCAT:f()"<<std::endl;}    
};    

int main()  
{  
    SMALLCAT sc;   

}  

output:

void CAT::f()  //not we expected!!!

Thanks

You have to throw individuals "C++ materials" towards the garbage bin.

You can call virtual functions in the constructor or destructor. Plus they is going to do their job. You just need to be familiar with the word what specs that clearly states that virtual dispatch mechanism works in compliance using the current dynamic kind of the item, avoid its final intended dynamic type. These kinds won't be the same to have an object being builtOrdamage, which frequently atmosphere newcomers once they make an effort to invoke virtual functions from constructors/destructors. Nonetheless, calling virtual functions from constructor and destructor is helpful feature from the language, as lengthy you may already know the things they're doing and just how they work in such instances. Why would you need to "prevent" it?

It is just like stating that division operator is harmful since it's possible to divide something by zero, and asking how you can "prevent" its use within this program.

You are able to call an online function in the destructor. Only in some cases it will not work, and could crash your program. The best way to avoid giving them a call would be to not give them a call. There is nothing more inticate I understand of, apart from possibly some static analysis tools to check out your code and warn you of potential issues such as this.

You CAN call an online function in the ctor/dtor. The problem is your vtable is to establish in every constructor (and destructor), so that your virtual function call will call the implementation from the class that's presently being setup. If that is what you would like, awesome. However you might as well save the vtable research and perform a scoped function call.