Reputation: 7948
I'm trying to override a method of the base class used by another method in the base class; however, when the derived class invokes the using-method of the base class, the derived used-method is never executed, but instead the base class's used-method is called. Here's an example:
#include <iostream>
using namespace std;
class Base {
public:
Base() {}
virtual ~Base() {}
void printLeft() { cout << this->getLeft(); }
int getLeft() { return 0; }
};
class Derived: public Base {
public:
Derived() {}
virtual ~Derived() {}
int getLeft() { return 1; }
};
int main(int argc, char *argv[]) {
Derived d = Derived();
d.printLeft();
}
Running main()
prints 0
, indicating Base
's getLeft()
method was used rather than the derived object's method.
How can I change this code so Derived::getLeft()
is called when called from an instance of Derived?
Upvotes: 2
Views: 4237
Reputation: 8815
For non-virtual functions, the static type of the object is used to determine which class's method is called.
In your case, you are calling getLeft()
from Base::printLeft()
. The type of this
is Base*
, so the function called will be Base::getLeft()
.
The way around this is to use the virtual
keyword. In that case, the virtual function table will be used to determine which version of getLeft()
to call, in this case Derived.
You can trigger this behavior by prepending virtual
to the declarations of printLeft
in both Base
and Derived
.
Upvotes: 1
Reputation: 25828
You just need to make getLeft
virtual:
class Base {
public:
Base() {}
virtual ~Base() {}
void printLeft() { cout << this->getLeft(); }
virtual int getLeft() { return 0; }
};
By default in C++ , member functions are not virtual. That is, you can't override them in a subclass.
Upvotes: 6