Create a C++ class for a student object with the following attributes—roll no, name, number of subjects , marks of subjects. The number of subjects varies for each student. Write a parameterized constructor which initializes roll number, name and number of subject and creates the array for marks dynamically, write member function for accepting marks and display all information of student.


#include<iostream.h>
#include<string.h>
#include<conio.h>

class student
{
  int rollno;
  char name[20];
  int no_of_sub;
  int *m;

  public:
  student() {}
  student(int r,char n[],int nos)
  {
   rollno=r;
   strcpy(name,n);
   no_of_sub=nos;
   accept();
  }

  void accept()
  {
    m=new int[no_of_sub];
    for(int i=0;i<no_of_sub;i++)
    {
      cout<<endl<<"Enter marks of Sub"<<i+1<<": ";
      cin>>m[i];
    }
  }

  void display()
  {
    cout<<endl<<"Roll: "<<rollno<<" Name: "<<name<<" No of Subjects: "<<no_of_sub;
    for(int i=0;i<no_of_sub;i++)
      cout<<" Marks of Sub"<<i+1<<": "<<m[i];
  }

};//end of class

int main()
{
  int n;
  student *s;
  clrscr();
  cout<<endl<<"Enter number of students: ";
  cin>>n;
  s=new student[n];
  for(int i=0;i<n;i++)
  {
    int r,nos;
    char n[20];
    cout<<endl<<"Enter roll,name,no of subjects: ";
    cin>>r>>n>>nos;
    s[i]=student(r,n,nos);
  }
  cout<<endl<<"Details of students are as follows: ";
  for(i=0;i<n;i++)
    s[i].display();
  getch();
  return 0;
}

No comments:

Post a Comment