Skip to content

Commit

Permalink
virtual call in constructor; warn when function is explicitly virtual
Browse files Browse the repository at this point in the history
  • Loading branch information
danmar committed Jul 11, 2021
1 parent f7b0f44 commit d9dacc9
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
2 changes: 2 additions & 0 deletions lib/checkclass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2421,6 +2421,8 @@ void CheckClass::checkVirtualFunctionCallInConstructor()
getFirstVirtualFunctionCallStack(virtualFunctionCallsMap, callToken, callstack);
if (callstack.empty())
continue;
if (!(callstack.back()->function()->hasVirtualSpecifier() || callstack.back()->function()->hasOverrideSpecifier()))
continue;
if (callstack.back()->function()->isPure())
pureVirtualFunctionCallInConstructorError(scope->function, callstack, callstack.back()->str());
else
Expand Down
3 changes: 1 addition & 2 deletions lib/checkclass.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ class CPPCHECKLIB CheckClass : public Check {
checkClass.virtualDestructor();
checkClass.checkConst();
checkClass.copyconstructors();
// FIXME: Only report warnings for inherited classes
// checkClass.checkVirtualFunctionCallInConstructor();
checkClass.checkVirtualFunctionCallInConstructor();
checkClass.checkDuplInheritedMembers();
checkClass.checkExplicitConstructors();
checkClass.checkCopyCtorAndEqOperator();
Expand Down
10 changes: 8 additions & 2 deletions test/testclass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6951,18 +6951,24 @@ class TestClass : public TestFixture {
" virtual int f() = 0;\n"
"};\n"
"class A : B {\n"
" int f();\n"
" int f();\n" // <- not explicitly virtual
" A() {f();}\n"
"};\n"
"int A::f() { return 1; }");
ASSERT_EQUALS("[test.cpp:6] -> [test.cpp:5]: (style) Virtual function 'f' is called from constructor 'A()' at line 6. Dynamic binding is not used.\n", errout.str());
ASSERT_EQUALS("", errout.str());

checkVirtualFunctionCall("class A\n"
"{\n"
" A() { A::f(); }\n"
" virtual void f() {}\n"
"};");
ASSERT_EQUALS("", errout.str());

checkVirtualFunctionCall("class A : B {\n"
" int f() final { return 1; }\n"
" A() { f(); }\n"
"};\n");
ASSERT_EQUALS("", errout.str());
}

void pureVirtualFunctionCall() {
Expand Down

0 comments on commit d9dacc9

Please sign in to comment.