Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to call a subclass function

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();
    }
}
like image 535
Jess Avatar asked Mar 26 '26 20:03

Jess


2 Answers

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;
like image 81
Daniel Kovachev Avatar answered Mar 29 '26 09:03

Daniel Kovachev


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/

like image 39
AresCaelum Avatar answered Mar 29 '26 09:03

AresCaelum