hey,
I've two classes and one class inherit the first class. I'm trying to add objects to vector (could be parent or child) and then call the overriding function (print) to display values passed in their respective constructors. But for some reasons only parent class' function (print) is invoked. I can't pinpoint the problem so I would appreciate if someone can help me, thanking in advance! I'm sharing my code:
example.h
class parent
{
public:
char type;
parent (char vType);
virtual void print();
virtual ~parent();
};
class child : public parent
{
public:
string value;
child (char vType, string val);
void print();
};
example.cpp
#include <iostream>
#include <string>
using namespace std;
#include "example.h"
parent::parent(char vType) {
parent::type = vType;
}
void parent::print() {
cout << parent::type << endl;
}
parent::~parent() { }
child::child (char vType, string val):parent(vType) {
child::value = val;
}
void child::print() {
cout << child::type << ":" << child::value << endl;
}
main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "example.h"
int main() {
vector <parent> a;
a.push_back(parent('{'));
a.push_back(child('x', "test");
for (int i = 0; i < a.size(); i++) {
parent * p = &a.at(i);
p->print();
}
return 0;
}