Example:1
Write a C++ program to declare a class named student with attributes as roll, name, and age, further take input for details and display them?
Sol:
//destructor functions #include<iostream> #include<conio.h> #include<string.h> using namespace std; class student { int roll; char name[20]; float age; public: student();//default constructor student(int r,char *n,float a);//para cons student(student &s);//copy constructor ~student();//destructor void read(); void show(); }; //default constructor student::student() //defa cons { roll=0; name[0]='\0'; age=0; } //para cons student::student(int r,char *n,float a)//para cons//1 { roll=r; strcpy(name,n); age=a; } //copy cons student::student(student &s) { roll=s.roll; strcpy(name,s.name); age=s.age; } //destructor student::~student() { cout<<"memory related to "<<name<<" is released"<<endl; cout<<roll<<" "<<name<<" "<<age<<endl; //getch(); } void student::read() { cout<<"Enter roll,name and age "; cin>>roll>>name>>age; } void student::show() { cout<<"roll "<<roll<<" name "<<name<<" age "<<age<<endl; } int main() { student s1,s2,s3; s1.read();s2.read();s3.read(); s1.show();s2.show();s3.show(); getch(); return(0); }
/* Output */ Enter roll,name and age 101 Amit 12 Enter roll,name and age 102 Sumit 14 Enter roll,name and age 103 Kapil 16 roll 101 name Amit age 12 roll 102 name Sumit age 14 roll 103 name Kapil age 16 memory related to Kapil is released 103 Kapil 16 memory related to Sumit is released 102 Sumit 14 memory related to Amit is released 101 Amit 12