From d9dacc97e41db71a5760eecfb76231432b14cf43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sun, 11 Jul 2021 11:03:09 +0200 Subject: [PATCH] virtual call in constructor; warn when function is explicitly virtual --- lib/checkclass.cpp | 2 ++ lib/checkclass.h | 3 +-- test/testclass.cpp | 10 ++++++++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index 786f1e5a7..fa2c05023 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -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 diff --git a/lib/checkclass.h b/lib/checkclass.h index 390fa723a..7aa00d140 100644 --- a/lib/checkclass.h +++ b/lib/checkclass.h @@ -70,8 +70,7 @@ public: checkClass.virtualDestructor(); checkClass.checkConst(); checkClass.copyconstructors(); - // FIXME: Only report warnings for inherited classes - // checkClass.checkVirtualFunctionCallInConstructor(); + checkClass.checkVirtualFunctionCallInConstructor(); checkClass.checkDuplInheritedMembers(); checkClass.checkExplicitConstructors(); checkClass.checkCopyCtorAndEqOperator(); diff --git a/test/testclass.cpp b/test/testclass.cpp index f7ce4b2e7..5208bf366 100644 --- a/test/testclass.cpp +++ b/test/testclass.cpp @@ -6951,11 +6951,11 @@ private: " 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" @@ -6963,6 +6963,12 @@ private: " 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() {