Computer Science/C++
[C++] Virtual Functions
focalpoint
2024. 9. 28. 04:34
https://www.hackerrank.com/challenges/virtual-functions/problem?isFullScreen=true
Virtual Functions | HackerRank
Learn how to use virtual functions and solve the given problem.
www.hackerrank.com
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Person {
public:
string name;
int age;
Person() {}
virtual void getdata() {};
virtual void putdata() {};
virtual ~Person() {}
};
class Professor : public Person {
public:
static int id;
int cur_id;
int publications;
Professor() : Person() {
Professor::id++;
cur_id = Professor::id;
}
virtual void getdata() override {
string _name;
int _publications;
int _age;
cin >> _name;
cin >> _publications;
cin >> _age;
this->name = _name;
this->publications = _publications;
this->age = _age;
}
virtual void putdata() override {
cout << this->name << " ";
cout << this->publications << " ";
cout << this->age << " ";
cout << this->cur_id << endl;
}
};
class Student : public Person {
public:
static int id;
int cur_id;
int marks[6];
int marks_total {0};
Student() : Person() {
Student::id++;
cur_id = Student::id;
}
virtual void getdata() override {
string _name;
int _age;
cin >> _name;
cin >> _age;
this->name = _name;
this->age = _age;
for (int i=0; i<6; i++) {
cin >> marks[i];
marks_total += marks[i];
}
}
virtual void putdata() override {
cout << this->name << " ";
cout << this->age << " ";
cout << this->marks_total << " ";
cout << this->cur_id << endl;
}
};
int Professor::id {0};
int Student::id {0};
int main(){
int n, val;
cin>>n; //The number of objects that is going to be created.
Person *per[n];
for(int i = 0;i < n;i++){
cin>>val;
if(val == 1){
// If val is 1 current object is of type Professor
per[i] = new Professor;
}
else per[i] = new Student; // Else the current object is of type Student
per[i]->getdata(); // Get the data from the user.
}
for(int i=0;i<n;i++)
per[i]->putdata(); // Print the required output for each object.
return 0;
}