mercredi 26 juillet 2017

C++ polymorphism Storing Base Class pointer in a vector

I have a base class and then two derived classes from it. I am using pointer of base class to store derived classes objects in Vector. Now I have to print the data stored in vector

how can I retrieve the objects from the vector.

How can I make sure to which derived class an object retrieved belongs.

class SlumsMember
    {



 protected:

   int rollNumber;
   string name;
   double gpa;
   char type;
};



class CricketPlayer:public SlumsMember
{
    protected:
        int runsScored;
        int wicketsTaken;
        int catchesTaken;


};



class FootballPlayer:public SlumsMember
{
 protected: 
    int goalsScored;
    int assists;
    int interceptions;

};

Here I am using vector to store objects inside a vector.

int main() {

vector<SlumsMember> members;

SlumsMember *slumsMember;

                    slumsMember=new FootballPlayer(rNo,name,gpa,ch,a,b,c);


                    slumsMember=new CricketPlayer(rNo,name,gpa,ch,a,b,c);





            members.push_back(*slumsMember);

SlumsMember *mbr;
 for(int i=0;i<members.size();i++)
 {
    mbr=members[i];

  //How to make sure to which base class an object retrieved belongs to and how to access it.

 }     







return 0;
}

Aucun commentaire:

Enregistrer un commentaire