Need help with a C++ assignment? Get affordable C++ homework help.

Inheritance code snippet

Summary

Source code of C++ program, demonstrating inheritance mechanism. Class Student is inherited from class Person and has extra field, extra method and slightly changed constructor.

Source code

C++: inheritance.cpp

#include <iostream>

#include <string>

 

using namespace std;

 

class Person {

public:

      Person(string name, int age) {

            this->name = name;

            this->age = age;

      }

      string getName() {

            return name;

      }

      int getAge() {

            return age;

      }

private:

      string name;

      int age;

};

 

// class Student is inherited from class Person

// it has extra field to store grade

// one extra method to read grade

// and slightly changed constructor

class Student : public Person {

public:

      // constuctor for class Student

      // calls super constructor for class Person

      Student(string name, int age, float grade) : Person(name, age) {

            this->grade = grade;

      }

      float getGrade() {

            return grade;

      }

private:

      float grade;

};

 

int main() {

      cout << "Creating a student..." << endl;

      Student johnDoe("John Doe", 25, 5.0);

      cout << "Student's name: " << johnDoe.getName() << endl;

      cout << "Student's age: " << johnDoe.getAge() << endl;

      cout << "Student's grade: " << johnDoe.getGrade() << endl;

 

      return 0;

}

 

Sample run

C/C++

Creating a student...
Student's name: John Doe
Student's age: 25
Student's grade: 5