3

I'm trying to come up with a way of checking in the derived class whether a method of the base class is defines 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 do I implement this MAGIC_CHECK? One solution for this could be using -Woverloaded-virtual compilation flag. Can anyone suggest a solution that will not involve this flag?

Thanks!

Vadim S.
  • 187
  • 1
  • 4

2 Answers2

3

In C++11 it's possible to add override at the end of the function declaration in the class and it will yield a warning if the function doesn't override anything:

class B : public A {
  virtual void vfoo() override { //OK
  }
  virtual void foo() override { //error
  }
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

In C++03 standard, it's not possible to check if a method is declared as virtual or not.
You may follow,

  • coding standards
  • peer review
  • possibly some static analysis tool
iammilind
  • 68,093
  • 33
  • 169
  • 336