简体   繁体   中英

Multilevel Inheritance and Polymorphism

class Player
{

protected:

  string type;
  int rank;

public:

  virtual void printType()
  {
      cout<<"Calling Class Player, type is: general Player"<<endl;
  }

};


//class FootballPlayer: Derived from Player

class FootballPlayer: public  Player 
{

protected:

public:

  virtual void printRank()
  {
    cout<<"Calling Class FootballPlayer, Rank is: Football Player rank"<<endl;

  }  

  void printType()
  {
    cout<<"Calling Class FootballPlayer, type is: Football Player"<<endl;
  }
};

class MaleFootballPlayer: public FootballPlayer  
{
public:

  void printType()
  {
    cout<<"Calling Class MaleFootballPlayer, type is: Male Football Player"<<endl;
  }


  void printRank()
  {
    cout<<"Calling Class MaleFootballPlayer, Rank is: Male Player rank"<<endl;

  }

};

//class CricketPlayer: Derived from Player

class CricketPlayer: public Player
{

protected:

public:

  void printType()
  {
    cout<<"Calling Class CricketPlayer, type is: Cricket Player"<<endl;
  }
};


int  main(int argc, const char * argv[])
{

  FootballPlayer fbplayer;
  CricketPlayer crplayer;
  MaleFootballPlayer malefbplayer;


  FootballPlayer *fbplayerPtr;
  fbplayerPtr=&malefbplayer;
  fbplayerPtr->printType();


  return 0; 
} 

AS I run the program, the output I get is,

Calling Class MaleFootballPlayer, type is: Male Football Player

I am creating a base class pointer (footballplayer) and assigning to derived class object(malefootballplayer), it should call the function belonging to base class(as it is not made virtual) and the output should have been ' calling class FootBallPlayer, type is: Football Player'.

Wish to get my concepts cleared.

Thanks.

Since the MaleFootballPlayer object's address is contained in the FootballPlayer type pointer and the printType() method declared as virtual in the base implementation, this is overriden runtime by the derived class MaleFootballPlayer function. Thats why this happened. Virtual table contains for pointers for both printType() functions of both class, but runtime the derived class printType() function pointer was chosen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM