In the following toy example, I have a base class and a class which inherits from it. The child class overrides the method doSomething()
. However when I pass an instance of the child class to a function expecting the base class, I get the behavior of the base class, i.e the output is I'm the base class!
rather than I'm the child class!
. How can I prevent this from happening and why does it happen (I guess there is some sort of implicit casting going on?).
Many thanks!
#include <iostream>
using namespace std;
class BaseClass {
public:
void doSomething() {
cout << "I'm the base class!";
}
};
class SubClass : public BaseClass {
public:
void doSomething() {
cout << "I'm a child class!";
}
};
void thisFunction(BaseClass & instance) {
instance.doSomething();
}
int main(int, char*[]) {
SubClass sc;
thisFunction(sc);
}