Allocated some memory-
buf = new char[sizeof(student_rec)*5];//student_rec is class
Then create an array of class 'student_rec' using placement new.
student_rec *sr1;
sr1 = new(buf)student_rec[5];
Call the method fun() for each class.
for(i=0; i<5; i++)
{
sr1[i].fun();
}
And after that call the destructor for each class.
i = 5;
while(i)
sr1[--i].~student_rec();
And delete the allocated memory chunk using delete.
delete [] buf;
Then why after that using sr1[2].fun() it prints 'hello' ? When i delete the memory using delete [] buf then there is no memory present for object. Then why sr1[2] works fine ?
Here is my code-
class student_rec
{
private:
string name;
int roll_no;
float percentage;
public:
student_rec()
{
cout<<"zero argument constructure\n";
}
~student_rec()
{
cout<<"destructure\n";
}
student_rec(char *n, int r, float per)
{
cout<<"three argument constructure\n";
name = n;
roll_no = r;
percentage = per;
}
void show()
{
cout<<"Name= "<<name<<endl;
cout<<"Roll No.= "<<roll_no<<endl;
cout<<"Percentage= "<<percentage<<endl;
}
void fun()
{
cout<<"hello\n";
}
};
int main()
{
char *buf;
buf = new char[sizeof(student_rec)*5];
student_rec *sr1;
sr1 = new(buf)student_rec[5];
int i;
for(i=0; i<5; i++)
{
sr1[i].fun();
}
i = 5;
while(i)
sr1[--i].~student_rec();
delete [] buf;
sr1[2].fun();
return 0;
}