sheffield

Inheritance C++ Derived class

Jul 14th, 2021 (edited)
957
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. // Online C++ compiler to run C++ program online
  2. using namespace std;
  3. #include <iostream>
  4. #include <string>
  5.  
  6. class Person {
  7.    
  8.    
  9. public:
  10.     string m_name;
  11.     int m_age;
  12.    
  13.     Person(const std::string& name = "", int age = 0)
  14.         : m_name{ name }, m_age{ age }
  15.     {
  16.     }
  17.  
  18.     const std::string& getName() const { return m_name; }
  19.     int getAge() const { return m_age; }
  20.    
  21. };
  22.  
  23. //  Making FootballPlayer a derived class
  24.  
  25. /*
  26.     To have FootballPlayer inherit from our Person class, the syntax is:
  27.     After the class FootballPlayer declaration, we use a colon, the word
  28.     “public”, and the name of the class we wish to inherit.
  29.    
  30.     This is called public inheritance.
  31. */
  32.  
  33. class FootballPlayer : public Person {
  34.     public:
  35.         int m_caps;
  36.         int m_goals;
  37.         FootballPlayer(int caps = 0, int goals = 0 )
  38.         : m_caps{caps}, m_goals{goals}
  39.         {}
  40.         int getCaps() const { return m_caps; }
  41.         int getGoals() const { return m_goals; }
  42. };
  43. /*
  44.     When FootballPlayer inherits from Person, FootballPlayer acquires the
  45.     member functions and variables from Person. Additionally, FootballPlayer
  46.     defines two members of its own: m_caps and m_goals.
  47.    
  48.     This makes sense, since these properties are specific to a FootballPlayer
  49.     , not to any Person.
  50. */
  51.  
  52. int main() {
  53.     // Create the object
  54.     Person person0;
  55.     Person person1("Harry Kane", 27);
  56.     Person person2("Steph Houghton", 33);
  57.    
  58.     // Call getdetails method
  59.     cout<<person1.getName()<<", "<<person1.getAge()<<endl;
  60.     cout<<person2.getName()<<", "<<person2.getAge()<<endl;
  61.    
  62.     FootballPlayer player1(61,37);
  63.     player1.m_name = "Harry Kane";
  64.     player1.m_age = 27;
  65.     cout<<player1.getName()<<", "<<player1.getAge()<<" ,Caps: "<<player1.getCaps()<<" ,Goals: "<<player1.getGoals()<<endl;
  66.    
  67.  
  68.     return 0;
  69. }
Add Comment
Please, Sign In to add comment