Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 86968e5

Browse files
Virtual Functions Problem
1 parent 295c680 commit 86968e5

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

‎HackerRank Practice/virtual_fns.cpp‎

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /