Reputation: 4540
Maybe a silly question.
Suppose I have the following:
class A{
int x;
int y;
virtual int get_thing(){return x;}
};
class B : public A {
int get_think(){return y;}
};
In the example above, B::get_thing returns x because the overriding code has a typo.
How can I ensure, at compile time that the get_thing function has been overridden in class B so that it returns y?
Upvotes: 1
Views: 286
Reputation: 227578
Assuming A::get_thing
is virtual, and assuming class B
is derived from class A
, and you have C++11 support, you can use the override
special identifier:
class B : public A{
int get_think() override {return y;}
};
This would produce a compiler error. Note that this is based on the signature of the method, i.e. its name, cv qualifiers, and types of the parameters. The return type or the body of the function do not come into it.
Upvotes: 8
Reputation: 6914
First you have an error in your example, I think B
supposed to be a child of A
, isn't it?!
But answer is: you can compare address of functions( of course if you want it and can't check it in programming time ):
if( reinterpret_cast<void*>(&B::get_think) != reinterpret_cast<void*>(&A::get_think) ) {
std::cout << "B override A";
} else {
std::cout << "B override A";
}
Upvotes: -1