HackerRank C++ Virtual Functions




This problem is to get you familiar with virtual functions. Create three classes Person, Professor and Student. The class Person should have data members name and age. The classes Professor and Student should inherit from the class Person.

The class Professor should have two integer members: publications and cur_id. There will be two member functions: getdata and putdata. The function getdata should get the input from the user: the name, age and publications of the professor. The function putdata should print the name, age, publications and the cur_id of the professor.



  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7. class Person {
  8. protected:
  9. std::string name;
  10. int age;
  11. int cur_id;
  12. public:
  13. Person()
  14. : name(""), age(0), cur_id(0)
  15. { }
  16. virtual void getdata() { cin >> name >> age; }
  17. virtual void putdata() { cout << name << " " << age << endl; }
  18. };
  19. class Professor : public Person {
  20. int publications;
  21. static int id;
  22. public:
  23. Professor()
  24. : publications(0)
  25. { cur_id = ++id; }
  26. void getdata() override { cin >> name >> age >> publications; }
  27. void putdata() override { cout << name << " " << age << " " << publications
  28. << " " << cur_id << endl; }
  29. };
  30. int Professor::id = 0;
  31. class Student : public Person {
  32. int marks[6];
  33. static int id;
  34. int marksSum;
  35. public:
  36. Student()
  37. : marks{0}, marksSum(0)
  38. { cur_id = ++id; }
  39. void getdata() override {
  40. cin >> name >> age;
  41. for (int i=0; i < 6; i++) {
  42. cin >> marks[i];
  43. }
  44. }
  45. void putdata() override {
  46. for(int i : marks)
  47. marksSum += i;
  48. cout << name << " " << age << " " << marksSum << " " << cur_id << endl;
  49. }
  50. };
  51. int Student::id = 0;
  52. int main(){
  53. int n, val;
  54. cin>>n; //The number of objects that is going to be created.
  55. Person *per[n];
  56. for(int i = 0;i < n;i++){
  57. cin>>val;
  58. if(val == 1){
  59. // If val is 1 current object is of type Professor
  60. per[i] = new Professor;
  61. }
  62. else per[i] = new Student; // Else the current object is of type Student
  63. per[i]->getdata(); // Get the data from the user.
  64. }
  65. for(int i=0;i<n;i++)
  66. per[i]->putdata(); // Print the required output for each object.
  67. return 0;
  68. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube