So I have a ParentClass and a ChildClass. I have a vector objects. I pushed back two items in it, a ParentClass newparent object and a ChildClass newchild object. I have a for-each loop and I want to access the child version function of the parent function from within this for-each loop but I cant. Please help.
here is the code:
#include <iostream>
#include <vector>
using namespace std;
class ParentClass {
public:
int _a;
ParentClass(int a) {
this->_a = a;
}
void print_a() {
cout << "parent a: " << this->_a << endl;
}
};
class ChildClass: public ParentClass {
public:
ChildClass(int a) : ParentClass(a) {}
void print_a(){
cout << "child a: " << this->_a << endl;
}
};
int main(int argc, char const *argv[]) {
int x = 5, y = 6;
vector<ParentClass> objects;
ParentClass newparent(x); objects.push_back(newparent);
ChildClass newchild(y); objects.push_back(newchild);
for (auto obj : objects){
obj.print_a();
}
return 0;
}
I want it to print out "child a: 6", but it prints out "parent a: 5" and "parent a: 6"