I am using a third party library with this class hierarchy:
A <- B <-C
I write my own class D as a subclass of C, and I want to override function foo() that is defined in some class of the parent hierarchy:
class D : public C {
void foo() override;
}
Assuming documentation for the parent hierarchy is lousy – Is there some way to know which class of the parent hierarchy also defines foo()?
Thanks!
10
Here are two ways in one example that cause the compiler to tell you in the error messages which function is overridden:
struct A {
virtual int foo(int);
};
struct B : A {
};
struct C : B {
char foo(int) override {
// ^^^ error: incorrect return value
// overridden function is listed
return B::foo();
// ^^^ error: incorrect arguments for base class version
// candidates are listed
}
};
And these are the errors:
<source>:9:10: error: conflicting return type specified for 'virtual char C::foo(int)'
9 | char foo(int) override {
| ^~~
<source>:2:17: note: overridden function is 'virtual int A::foo(int)'
2 | virtual int foo(int);
| ^~~
<source>: In member function 'virtual char C::foo(int)':
<source>:12:22: error: no matching function for call to 'C::foo()'
12 | return B::foo();
| ~~~~~~^~
<source>:2:17: note: candidate: 'virtual int A::foo(int)'
2 | virtual int foo(int);
| ^~~
<source>:2:17: note: candidate expects 1 argument, 0 provided
If what you want is to check at compile time whether a derived class overrides its parent’s method or not and you know the names of the classes and the method, you can use the following concept:
template <typename Base, typename Derived>
concept override_foo =
std::is_same_v<decltype(&Base::foo), decltype(&Derived::foo)> == false;
Demo
1