Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

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

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();
    }
}
question from:https://stackoverflow.com/questions/65870979/cppdepend-rule-constructor-should-not-call-a-virtual-methods-only-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...