1

I have a base class called Base and 2 derived classes called Derived and Combined. Combined takes in 2 instances of Derived class. When I run Combined.Run(input), the virtual function Update is being overridden, which is what I want. However, when I run B1.Update(B1.x) and B2.Update(B2.x) (within Combined.Update()), the virtual function Update are not being overridden. I want Derived.Update() to be called when I run B1.Update(B1.x). How can I fix this? Below is the code and console output. Thank you in advance.

#include <iostream>
#include <vector>
using namespace std;

class Base {
public:
    vector<int> x;

    Base(vector<int> x0) : x(x0) {}

    virtual int Update(vector<int> x) {
        cout << "Base Update" << endl;
        return 0;
    }

    int Run(int input) {
        return Update(x) + input;
    }
};

class Derived : public Base {
public:
    Derived(vector<int> x0) : Base(x0) {}

    int Update(vector<int> x) {
        cout << "Derived Update" << endl;
        return x[0];
    }
};


class Combined : public Base {
public:
    Base B1;
    Base B2;
    Combined(Base& b1, Base& b2)
        : Base({ 0, 0 }), B1(b1), B2(b2) {}

    int Update(vector<int> x) {
        cout << "Combined Update" << endl;
        return B1.Update(B1.x) + B2.Update(B2.x);
    }
};

int main() {
    Derived D1({0});
    Derived D2({0});
    Combined C(D1, D2);
    int input = 5;

    cout << "Output = " << C.Run(input) << endl;
}

Console output:

Combined Update
Base Update
Base Update
Output = 5

What I want:

Combined Update
Derived Update
Derived Update
Output = 5
Edwin R
  • 11
  • 1
  • 3
    TL;DR of the dupe: `b1` and `b2` are declared as type `Base`. That means you are always dealing with a `Base`. You need a `Base&` or `Base*` to get polymorphism. – NathanOliver Aug 04 '21 at 20:48
  • You should also make the method ```Run()``` virtual in the base class, and ```override``` that method in the ```Derived``` and ```Combined``` class if necessary – Job_September_2020 Aug 04 '21 at 20:57
  • I'm not sold on *should* in *You should also make the method Run() virtual*. If the use case is "`Run` does s bunch of common stuff and then call overridden functions for derived-specific behaviour." then Asker's implementation will keep duplication down. If eveyone has a radically different `Run` behaviour with little commonality, then `virtual` `Run` makes more sense. – user4581301 Aug 04 '21 at 21:15

0 Answers0