In this HackerRank Virtual Functions problem in c++, we need to create three classes Person, Professor, and Student. The class Person should have data members' names and ages. The classes Professor and Student should inherit from the class Person.

HackerRank Virtual Functions in C++ problem solution

HackerRank Virtual Functions in C++ problem solution

class Person {
protected:
    string name;
    int id;
    int age;
public:
    virtual int nextId() = 0;
    virtual void getdata() {
        id = nextId();
        cin >> name >> age;
    }
    virtual void putdata() {
        cout << name << " " << age;
    }
};

class Professor: public Person {
    static int pId;
    int publications;
public:
    virtual int nextId() {
        return ++pId;
    }
    virtual void getdata() {
        Person::getdata();
        cin >> publications;
    }
    virtual void putdata() {
        Person::putdata();
        cout << " " << publications << " " << id << endl;
    }
};
int Professor::pId = 0;

class Student: public Person {
    static int sId;
    int marks;
public:
    Student() :marks(0) {}
    virtual int nextId() {
        return ++sId;
    }
    virtual void getdata() {
        Person::getdata();
        for (int i = 0; i < 6; i++) {
            int t;
            cin >> t;
            marks += t;
        }
    
    }
    virtual void putdata() {
        Person::putdata();
        cout << " " << marks << " " << id << endl;
    }
};
int Student::sId;