Heyo, I'm a little confused about how method overriding works when you involve calling objects as their parent type.
Here is my example code:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
class A {
public:
A() {
std::cout << "Made A.\n";
}
void doThing() {
std::cout << "A did a thing.\n";
};
};
class B : public A {
public:
B() {
std::cout << "Made B.\n";
}
void doThing() {
std::cout << "B did a thing.\n";
};
};
class C : public A {
public:
C() {
std::cout << "Made C.\n";
}
void doThing() {
std::cout << "C did a thing.\n";
};
};
int main(int argc, char** argv) {
std::cout << "\n";
std::cout << "Make objects: \n";
A a;
B b;
C c;
std::cout << "Call objects normally: \n";
a.doThing();
b.doThing();
c.doThing();
std::cout << "Call objects as their parent type from a vector: \n";
vector<A> vect;
vect.push_back(a); vect.push_back(b); vect.push_back(c);
for(int i=0;i<vect.size();i++)
vect.data()[i].doThing();
return 0;
}
And here is the output I get:
Make objects:
Made A.
Made A.
Made B.
Made A.
Made C.
Call objects normally:
A did a thing.
B did a thing.
C did a thing.
Call objects as their parent type from a vector:
A did a thing.
A did a thing.
A did a thing.
This same code in another language (like Java) would produce this output:
Make objects:
Made A.
Made B.
Made C.
Call objects normally:
A did a thing.
B did a thing.
C did a thing.
Call objects as their parent type from a vector:
A did a thing.
B did a thing.
C did a thing.
In short, how do I achieve that second output in c++?