We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
class Professor : public Person {
private:
int publications;
static int idCounter;
public:
Professor() : Person(++idCounter) {}
void getdata() override {
cin >> name >> age >> publications;
}
void putdata() override {
cout << name << " " << age << " " << publications << " " << cur_id << endl;
}
};
int Professor::idCounter = 0;
class Student : public Person {
private:
int marks[6];
static int idCounter;
public:
Student() : Person(++idCounter) {}
void getdata() override {
cin >> name >> age;
for (int i = 0; i < 6; i++) {
cin >> marks[i];
}
}
void putdata() override {
int sum = 0;
for (int i = 0; i < 6; i++) {
sum += marks[i];
}
cout << name << " " << age << " " << sum << " " << cur_id << endl;
}
};
int Student::idCounter = 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;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Virtual Functions
You are viewing a single comment's thread. Return to all comments →
include
include
include
include
include
using namespace std;
class Person { protected: int age; string name; int cur_id;
public: Person(int cur_id) : cur_id(cur_id) {} virtual void getdata() = 0; virtual void putdata() = 0; virtual ~Person() = default; // Virtual destructor for proper cleanup };
class Professor : public Person { private: int publications; static int idCounter;
public: Professor() : Person(++idCounter) {}
};
int Professor::idCounter = 0;
class Student : public Person { private: int marks[6]; static int idCounter;
public: Student() : Person(++idCounter) {}
};
int Student::idCounter = 0; int main(){
}