Friday 17 April 2015

Live Objects


Objects created dynamically with their data members initialized during creation are known as Live Objects. To create a live object, constructor must be invoked automatically which performs initialization of data members. Similarly the destructor for an object must be invoked automatically before the memory for that object is deallocated.

A class whose live object is to be crated must have atleast one constructor. The syntax for
creating a live object is as follows.

Pointer_to_Object = new Class_name(Parameters)


Sample Program

#include <iostream.h>
#include <string.h>
class student
{
int rno;
char *name;
public:
studen(void)
{
char flag, str[50];
cout<<”Do u want to initialize the object y/n”;
cin>>flag;
if(flag == ‘y’)
{
cout<<”Enter the student number”;
cin>>rno;
cout<<”Enter the student name”;
cin>>name;
}


else
{
rno =0;
name = NULL;
}
}
student(int rn)
{
rno = rn;
name = NULL;
}
student(int rn, char *n)
{
rno = rn;
name = n;
}
~student()
{
if(name)
delete name;
}
void show(void)
{
if(rno)
cout<<”Roll number is”<<rno<<endl;
else
cout<<”Number not initialized”<<endl;
if(name)
cout<<”Student name is “<<name<<endl;
else
cout<<”Name not initialized”<<endl;
}
};
void main()
{
student *s1, *s2, *s3;
s1 = new student;
s2 = new student(1);
s3 = new student(1,”Magesh”);
cout<<”Live objects contents………….”<<endl;
s1->show();
s2->show();
s3->show();
delete s1;
delete s2;
delete s3;
}




No comments:

Post a Comment