Checking compile time if a method defined as virtual is installed

I am trying to find a way to check in a derived class whether a base class method is defined as "virtual". Basically, I would like to have the following code:

class A { virtual void vfoo() {} void foo() {} virtual ~A() {} }; class B : public A { virtual void vfoo() { MAGIC_CHECK(m_pA->vfoo()); // succeed // code m_pA->vfoo(); // code } virtual void foo() { MAGIC_CHECK(m_pA->foo()); // fail compilation because foo is not virtual! // code m_pA->foo(); // code } A * m_pA; }; 

The question is how to implement this MAGIC_CHECK? One solution to this might be to use -Woverloaded-virtual compilation. Can someone suggest a solution that won't include this flag?

Thanks!

+3
source share
2 answers

In the C ++ 03 standard, it is not possible to check whether a method is declared as virtual or not.
You can follow

  • coding standards
  • expert review
  • possibly a static analysis tool
+1
source

In C ++ 11, you can add an override at the end of a function declaration in a class , and this will give a warning if the function does not override anything:

 class B : public A { virtual void vfoo() override { //OK } virtual void foo() override { //error } }; 
+3
source

Source: https://habr.com/ru/post/911842/


All Articles