Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time check of whether a method defined as virtual

Tags:

c++

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?

like image 877
Vadim S. Avatar asked Dec 30 '25 22:12

Vadim S.


1 Answers

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
  }
};
like image 95
Luchian Grigore Avatar answered Jan 02 '26 13:01

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!