C++ How to call a subclass function

2.3k views Asked by At

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();
    }
}
3

There are 3 answers

2
Daniel Kovachev On BEST ANSWER

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:

vector<A*> bb;
1
AresCaelum On

The issue here is in order for inheritance to work you need to use pointers. your vector is a vector<A> and not a vector<A*> so when you push-back the dereferences version of yy and zz you are pushing back the copy of their A data members not a copy of the B and C data members. The size of B and C is different then A so it will only do a copy of data members that will fit in the place of A object.

http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/

0
Ezra On

You can't expect polymorphism to work without pointers. Change your main part to

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();
}