c++constructoreclipse-cdtvirtual-functionsqualified-name

Is it safe to call a virtual method in the constructor when using a scope resolution operator?


I have a class hierarchy where every class has a method compute that will trigger some (re-) computation. This method is a virtual method (and it's pure virtual in the base class). In some cases I would like to call this method from the constructor to immediately set up my instance.

Of course this can be dangerous. Eclipse CDT Code Analysis issues the error "Calling a virtual method in constructor can cause crashes and unexpected behavior". I understand the error message and its reason. Please, please do not tell me why this should be avoided!!!

To make the error message and (more important) the potential of having an error go away, I have introduced a scope resolution operator. So the constructor now looks like that:

MyClass::MyClass()
{
    MyClass::compute();
}

I would expect that to be absolutely safe. But Eclipse code analysis continues to display the error message. Why? It is not possible to call an unexpected method. And if the method was pure virtual in MyClass, the compiler would tell me so.

Is this an Eclipse code analysis bug or am I missing something?

Edit: the scope resolution operator is supposed to suppress virtual resolution. Therefore I expect it to prevent all possible errors mentioned by the warning. Is my assumption true?


Solution

  • I would like to summarize the most important points from the comments/chat:

    1. The scope resolution operator can be used as a kind of annotation to indicate a suppression of virtual resolution. It actually has no effect, since in constructors (and destructors) the virtual call mechanism is disabled anyway. Since the potential for errors (execution of another method than the one expected by the user) is gone, no warning should be issued for that code. It is safe.
    2. Introducing a non-virtual "helper" method is an alternative. Then both, the constructor and the virtual method could delegate their task to the non-virtual method. This approach may appear less suspicious to those who want to stick to the rule "Avoid calling virtual methods from constructors or destructors." On the other hand it seems less elegant, since it makes the introduction of boilerplate helper methods necessary.