Question

Some C++ materials mention we can't call a virtual function inside ctor or dtor,

(
sorry ,I think it's better to change to
Some C++ materials mention we'd better not to call a virtual function inside ctor or dtor,

)

but we may call them accidentally. Is there any way to prevent that?

For example:

# 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

No correct solution

OTHER TIPS

You need to throw those "C++ materials" to the garbage bin.

You certainly can call virtual functions from the constructor or destructor. And they will do their job. You simply need to be aware of the language specification that clearly states that virtual dispatch mechanism works in accordance with the current dynamic type of the object, not with its final intended dynamic type. These types are not the same for an object under construction/destruction, which often confuses newbies when they attempt to invoke virtual functions from constructors/destructors. Nevertheless, calling virtual functions from constructor and destructor is useful feature of the language, as long as you know what they do and how they work in such cases. Why would you want to "prevent" it?

It is like saying that division operator is dangerous since one can divide something by zero, and asking how to "prevent" its use in the program.

You can call a virtual function inside a destructor. Only in certain cases it won't work, and may crash your program. The way to avoid calling them is to not call them. There's nothing fancier I know of, other than possibly some static analysis tools to look at your code and warn you of potential problems like this.

You certainly CAN call a virtual function inside a ctor/dtor. The issue is that your vtable is set up in each constructor (and destructor), so your virtual function call will call the implementation of the class that is currently being set up. If that's what you want, cool. But then you may as well save yourself the vtable lookup and do a scoped function call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top