virtual call in constructor; warn when function is explicitly virtual

This commit is contained in:
Daniel Marjamäki 2021-07-11 11:03:09 +02:00
parent f7b0f44186
commit d9dacc97e4
3 changed files with 11 additions and 4 deletions

View File

@ -2421,6 +2421,8 @@ void CheckClass::checkVirtualFunctionCallInConstructor()
getFirstVirtualFunctionCallStack(virtualFunctionCallsMap, callToken, callstack); getFirstVirtualFunctionCallStack(virtualFunctionCallsMap, callToken, callstack);
if (callstack.empty()) if (callstack.empty())
continue; continue;
if (!(callstack.back()->function()->hasVirtualSpecifier() || callstack.back()->function()->hasOverrideSpecifier()))
continue;
if (callstack.back()->function()->isPure()) if (callstack.back()->function()->isPure())
pureVirtualFunctionCallInConstructorError(scope->function, callstack, callstack.back()->str()); pureVirtualFunctionCallInConstructorError(scope->function, callstack, callstack.back()->str());
else else

View File

@ -70,8 +70,7 @@ public:
checkClass.virtualDestructor(); checkClass.virtualDestructor();
checkClass.checkConst(); checkClass.checkConst();
checkClass.copyconstructors(); checkClass.copyconstructors();
// FIXME: Only report warnings for inherited classes checkClass.checkVirtualFunctionCallInConstructor();
// checkClass.checkVirtualFunctionCallInConstructor();
checkClass.checkDuplInheritedMembers(); checkClass.checkDuplInheritedMembers();
checkClass.checkExplicitConstructors(); checkClass.checkExplicitConstructors();
checkClass.checkCopyCtorAndEqOperator(); checkClass.checkCopyCtorAndEqOperator();

View File

@ -6951,11 +6951,11 @@ private:
" virtual int f() = 0;\n" " virtual int f() = 0;\n"
"};\n" "};\n"
"class A : B {\n" "class A : B {\n"
" int f();\n" " int f();\n" // <- not explicitly virtual
" A() {f();}\n" " A() {f();}\n"
"};\n" "};\n"
"int A::f() { return 1; }"); "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" checkVirtualFunctionCall("class A\n"
"{\n" "{\n"
@ -6963,6 +6963,12 @@ private:
" virtual void f() {}\n" " virtual void f() {}\n"
"};"); "};");
ASSERT_EQUALS("", errout.str()); 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() { void pureVirtualFunctionCall() {