Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Online C++ compiler to run C++ program online
- using namespace std;
- #include <iostream>
- #include <string>
- class Person {
- public:
- string m_name;
- int m_age;
- Person(const std::string& name = "", int age = 0)
- : m_name{ name }, m_age{ age }
- {
- }
- const std::string& getName() const { return m_name; }
- int getAge() const { return m_age; }
- };
- // Making FootballPlayer a derived class
- /*
- To have FootballPlayer inherit from our Person class, the syntax is:
- After the class FootballPlayer declaration, we use a colon, the word
- “public”, and the name of the class we wish to inherit.
- This is called public inheritance.
- */
- class FootballPlayer : public Person {
- public:
- int m_caps;
- int m_goals;
- FootballPlayer(int caps = 0, int goals = 0 )
- : m_caps{caps}, m_goals{goals}
- {}
- int getCaps() const { return m_caps; }
- int getGoals() const { return m_goals; }
- };
- /*
- When FootballPlayer inherits from Person, FootballPlayer acquires the
- member functions and variables from Person. Additionally, FootballPlayer
- defines two members of its own: m_caps and m_goals.
- This makes sense, since these properties are specific to a FootballPlayer
- , not to any Person.
- */
- int main() {
- // Create the object
- Person person0;
- Person person1("Harry Kane", 27);
- Person person2("Steph Houghton", 33);
- // Call getdetails method
- cout<<person1.getName()<<", "<<person1.getAge()<<endl;
- cout<<person2.getName()<<", "<<person2.getAge()<<endl;
- FootballPlayer player1(61,37);
- player1.m_name = "Harry Kane";
- player1.m_age = 27;
- cout<<player1.getName()<<", "<<player1.getAge()<<" ,Caps: "<<player1.getCaps()<<" ,Goals: "<<player1.getGoals()<<endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment