Array type pointer object
Example:1
WAP declare a class named person with attributes as name and age. Take input for details of “n” persons check and print the details of the elder person.
Sol:
#include<iostream> #include<conio.h> #include<string.h> using namespace std; class person { private: char name[20]; int age; public: person(); //default person(char *n,int a); //para void read(); void show(); void setdata(char *n,int a); person elder(person p); }; person::person() { name[0]='\0'; age=0; } person::person(char *n,int a) { strcpy(name,n); age=a; } void person::read() { cout<<"Enter name and age "; cin>>name>>age; } void person::show() { cout<<"name "<<name<<" age "<<age<<endl; } void person::setdata(char *n,int a) { strcpy(name,n); age=a; } person person::elder(person p) { if(age>p.age) return(*this); else return(p); } //*this : represent the object using which the function is called int main() { int i; person p1,p[3]; p[0].setdata("amit",10); p[1].setdata("sumit",25); p[2].setdata("kapil",21); /*for(i=0;i<3;i++) { cout<<"Enter details of "<<i+1<<" Person"<<endl; p[i].read(); } */ p1=p[0]; for(i=0;i<3;i++) { p[i].show(); p1=p1.elder(p[i]); } cout<<"Details of Elder person"<<endl; p1.show(); getch(); return(0); }
Output:
name amit age 10
name sumit age 25
name kapil age 21
Details of Elder person
name sumit age 25
Example:2
Declare a class named student with attributes as roll, name and per. Take input for details of “n” students ,check and print the details of the student higher in the merit list.
Sol:
#include<iostream> #include<conio.h> #include<string.h> using namespace std; class student { private: int roll; char name[20]; float per; public: student();//default cons student(int r,char *n,float p); //para cons void setdata(int r,char *n,float p); void read(); void show(); student higher(student s); }; student::student() { roll=0; name[0]='\0'; per=0; } student::student(int r,char *n,float p) { roll=r; strcpy(name,n); per=p; } void student::setdata(int r,char *n,float p) { roll=r; strcpy(name,n); per=p; } void student::read() { cout<<"Enter roll,name and per "; cin>>roll>>name>>per; } void student::show() { cout<<"roll "<<roll<<" name "<<name<<" per "<<per<<endl; } student student::higher(student s) { if(per>s.per) return(*this); else return(s); } //*this : represent the object using which the function is called int main() { int i; student s1,s[3]; s[0].setdata(101,"amit",90); s[1].setdata(102,"sumit",95); s[2].setdata(103,"kapil",98); /*for(i=0;i<3;i++) { cout<<"Enter details of "<<i+1<<" Student"<<endl; s[i].read(); } */ s1=s[0]; for(i=0;i<3;i++) { s[i].show(); s1=s1.higher(s[i]); } cout<<"Details of Student Top in merit list"<<endl; s1.show(); getch(); return(0); }
Output:
roll 101 name amit per 90
roll 102 name sumit per 95
roll 103 name kapil per 98
Details of Student Top in merit list
roll 103 name kapil per 98