I want to use the derived class B::display()
and C::display()
, but it uses A::display()
. How do I change the code so that I can call the derived class' display()
to display the id
together with name
?
Thanks in advance :)
#include <iostream>
#include <vector>
using namespace std;
class A
{
protected :
int id;
public:
A ( int id = 0 ) : id(id) {}
virtual void display() { cout << id << endl; }
};
class B : public A
{
string name;
public:
B ( int id = 0, string name = "-" ) : A(id), name(name) {}
void display() { cout << id << " " << name << endl; }
};
class C : public A
{
string name;
public:
C ( int id = 0, string name = "-" ) : A(id), name(name) {}
void display() { cout << id << " " << name << endl; }
};
int main()
{
vector< vector <A> > aa;
vector<A> bb ;
vector<A> cc ;
A *yy = new B(111, "Patrick");
A *zz = new C(222, "Peter");
bb.push_back(*yy);
cc.push_back(*zz);
aa.push_back(bb);
aa.push_back(cc);
for ( int i = 0; i < aa[0].size(); i++)
{
aa[0][i].display();
aa[1][i].display();
}
}
your problem his that you are declartion of the vector is of non pointer type , and on runtime you are losing the "point" to the subclass and you just stay with the super class. all you have to do is change all of your vectors to pointer type , like that: