#include <iostream>
class FooChild
{
public:
FooChild(){}
virtual void doThis() {std::cout << "doThis Parent" << std::endl;}
virtual bool doThat(int n, double x) { std::cout << "doThat Parent" << std::endl; return false; }
};
class FooFighter
{
public:
void doSomething(FooChild &fooChild)
{
fooChild.doThis();
fooChild.doThat(4, 5);
}
void doSomethingPtr()
{
m_child->doThis();
m_child->doThat(4, 5);
}
void doSomethingREF()
{
r_child.doThis();
r_child.doThat(4, 5);
}
friend void setChild(FooFighter& obj, FooChild* child);
friend void setChild(FooFighter& obj, FooChild& child);
private:
FooChild* m_child;
FooChild r_child;
};
void setChild(FooFighter& obj, FooChild* child){
obj.m_child = child;
}
void setChild(FooFighter& obj, FooChild& child){
obj.r_child = child;
}
class MockFooChild : public FooChild
{
public:
void doThis() {std::cout << "doThis Child" << std::endl;}
bool doThat(int n, double x) { std::cout << "doThat Child" << std::endl; return false; }
};
int main(){
MockFooChild mockFooChild;
FooFighter fooFighter;
setChild(fooFighter, &mockFooChild);
setChild(fooFighter, mockFooChild);
std::cout << "Pointer is calling: \n";
fooFighter.doSomethingPtr();
std::cout << "Ref is calling: \n";
fooFighter.doSomethingREF();
std::cout << "Passing it by ref is calling: \n";
fooFighter.doSomething(mockFooChild);
}
https://godbolt.org/z/v7GdPWr5e
I expected the following output:
Pointer is calling:
doThis Child
doThat Child
Ref is calling:
doThis Child
doThat Child
Passing it by ref is calling:
doThis Child
doThat Child
but I am instead seeing:
Pointer is calling:
doThis Child
doThat Child
Ref is calling:
doThis Parent
doThat Parent
Passing it by ref is calling:
doThis Child
doThat Child
Why is MockFooChild's
function not getting called and the parent class' function is being used instead?