Search code examples
c++classobjectmethods

Is Overriding Methods From An Object Possible? C++


I was wondering if it is possible to override a method of an object ex:

class Object{
public:
  void Foo(){
  //do something
  }
};

Object* obj = new Object();

obj->Foo() {
//do something else
}

I tried to use a function variable but it still does not work.

Please some help, I feel like I am about to lose my braincells over this problem.


Solution

  • As mentioned by @Jarod42 in the comments I would add a std::function member, or some other callable. As an example (Godbolt)

    #include <functional>
    #include <iostream>
    #include <utility>
    
    class Object {
    public:
       Object(std::function<int(int)> do_work) : do_work_(std::move(do_work)) {}
    
       int DoWork(int i) { return do_work_(i); }
    
    private:
       std::function<int(int)> do_work_;
    };
    
    int main() {
      Object obj1{[](int i){ return i + 1;}};
      std::cout << obj1.DoWork(1) << '\n';
    
      Object obj2{[](int i){ return i - 1;}};
      std::cout << obj2.DoWork(1) << '\n';
    }
    

    You can see that DoWork invokes the callable, and each instance of the Object class is free to define what that work is.