(Cppdepend Rule) "Constructor should not call a virtual methods" only functions on own (base)class?

97 Views Asked by At

I have an question to "Constructor should not call a virtual methods" (in C++). Yes I know the problem. The problem is clear. It is described e.g. here

I have a special question. I start with CppDepent do check my project. Now CppDepent warns me, every time I call a virtual function in constructor. No matter if the function is on a base class or not. It warns if it is a virtual function of an other class. (see sample)

The question: Is it a Problem to call a virtual function on a constructor (same destructor) of an class how is not a base class.

class NotABaseClass {
    explicit NotABaseClass(){}

    virtual void foo_virtual(){};
}

class NotADeriveClass {

    explicit NotADeriveClass(){
        NotABaseClass notABaseClass;
        notABaseClass.foo_virtual();
    }
}
1

There are 1 best solutions below

0
On

The C++ rule says that you shall not call a virtual method on an object before that object if fully constructed.

In your example, the virtual method is called that way:

explicit NotADeriveClass(){  // we are in a ctor: *this is not fully constructed
    NotABaseClass notABaseClass;   // let us create a local NotABaseClass object
    notABaseClass.foo_virtual();   // legal on a fully constructed object
}

The problem of many tools trying to detect suspect expressions, if that they are created by mere humans and not gods. So they may sometimes fail to detect a problem (non detection) or croak on a legal one (false positive). Furthermore, a false positive is often seen as less serious, because the programmer has just to examine their code and ignore it. If you can make sure that a warning is just a false positive, you can often use a special comment to signal the tool that one specific rule is to be ignored at that special place to get rid of the warning. Just make sure to ignore as less as possible...