As I am practicing C++ with some of my colleagues, one of them "experienced a bug" within a derived class: long story short he was calling the base method (callFoo) and he was expecting to be calling A::Foo(); he got B::Foo() instead.
Here's a complete example of what I am actually asking, I don't really know how to explain better than this. I have indeed found a solution but it makes the code kind of hard to "sanitize", for the future extensions of our classes. Is there a keyword or something that I am missing?
n.b. The example is purely demonstrative: in the original example callFoo() was the operator= for "Class A", I tried my best to simplify it.
Example 1: Unwanted behavior
#include <iostream>
class A{
public:
virtual void Foo(){
std::cout<<"A Foo\n";
}
virtual void callFoo(){
Foo();
}
};
class B: public A{
public:
virtual void Foo() override{
std::cout<<"B Foo\n";
}
};
int main(){
B mB;
mB.Foo();
mB.callFoo();
return 0;
}
Example 2: The actual fix
class A{
public:
virtual void Foo(){
std::cout<<"A Foo\n";
}
virtual void callFoo(){
A::Foo();
}
};
Aucun commentaire:
Enregistrer un commentaire