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