I want to allocate new memory for my class which has some derived classes as well. as I have defined a constructor of type Professor(string name,int age,int publications,int cur_id)
memory allocation
per[i] = new Professor;
in the main throws error:no matching function for call to 'Professor::Professor()
.
another error I am getting is candidate: 'Professor::Professor(std::string, int, int, int)
expects 4 arguments, 0 provided. please help me how to define a constructor which allocates memory without giving any error, thanks.
ps: I am trying to solve this question
part of my class looks like;
class Person{
protected:
string name;
int age;
public:
Person(string name,int age){
name=name;
age=age;
}
int z=0;
void getdata(){
string m;int n;
cin>>m>>n;
z++;
Person(m,n);
}
void putdata(){
cout<<name<<" "<<age<<endl;
}
};
class Professor: public Person{
public:
int publications;
int cur_id;
Professor(string name,int age,int publications,int cur_id)
:Person(name,age)
{
publications=publications;
cur_id=cur_id;
}
int b=0;
void getdata(){
string a;int b,c;
cin>>a>>b>>c;
b++;
Professor(a,b,c,b);
}
void putdata(){
cout<<name<<" "<<age<<" "<<publications<<" "<<cur_id<<endl;
}
};
class Student:public Person{
public:
int marks[6];
int cur_id;
Student(string name,int age,int arr[6],int cur_id)
:Person(name,age)
{
marks[6]=arr[6];
cur_id=cur_id;
}
int s=0;
void getdata(){
string p;int q;int r[6];
cin>>p>>q;
for(int i=0;i<6;i++){
cin>>r[i];
}
s++;
Student(p,q,r,s);
}
void putdata(){
cout<<name<<" "<<age<<" "<<marks[0]<<" "<<marks[1]<<" "<<marks[2]<<" "<<marks[3]<<" "<<marks[4]<<" "<<marks[5]<<" "<<cur_id<<endl;
}
};
My main function looks like
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;
}