Reputation: 1276
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);
}
Upvotes: 2
Views: 430
Reputation: 38267
Your BaseClass::doSomething()
is not virtual. This way, it can't be overridden, but only shadowed. Try changing its signature to
class BaseClass {
virtual void doSomething() { /* ... */ }
};
No changes are required for the SubClass
, it is, however, good practice to make use of the override
keyword (your example code is a perfect illustration for this - marking the method with override
makes the compiler complain if the exact same function signature isn't virtual
in any base class) :
class SubClass : public BaseClass {
void doSomething() override { /* ... */ }
};
In addition to that, please make the BaseClass
destructor virtual, too (or protected
), or you risk undefined behavior when deleting a SubClass
instance through a BaseClass
pointer.
Upvotes: 5