c++ make the base class use overridden methods in the child class
c++, inheritance, polymorphism
Solution
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.
Problem
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?