InterviewSolution
| 1. |
Is It Possible For The Objects To Read And Write Themselves? |
|
Answer» Answer :Yes! This can be explained with the help of following example: #include #include class employee { private : char name [ 20 ] ; int age ; float salary ; PUBLIC : void GETDATA( ) { COUT << "Enter name, age and salary of employee : " ; cin >> name >> age >> salary ; } void store( ) { ofstream file ; file.open ( "EMPLOYEE.DAT", ios::app | ios::binary ) ; file.write ( ( char * ) this, sizeof ( *this ) ) ; file.close( ) ; } void retrieve ( int N ) { ifstream file ; file.open ( "EMPLOYEE.DAT", ios::binary ) ; file.seekg ( n * sizeof ( employee ) ) ; file.read ( ( char * ) this, sizeof ( *this ) ) ; file.close( ) ; } void show( ) { cout << "Name : " << name << endl << "Age : " << age << endl << "Salary :" << salary << endl ; } } ; void main( ) { employee e [ 5 ] ; for ( int i = 0 ; i <= 4 ; i++ ) { e [ i ].getdata( ) ; e [ i ].store( ) ; } for ( i = 0 ; i <= 4 ; i++ ) { e [ i ].retrieve ( i ) ; e [ i ].show( ) ; } } Here, employee is the class whose objects can write and read themselves. The getdata( ) function has been used to get the data of employee and store it in the data members name, age and salary. The store( ) function is used to write an object to the file. In this function a file has been opened in append mode and each time data of current object has been stored after the last record (if any) in the file.Function retrieve( ) is used to get the data of a particular employee from the file. This retrieved data has been stored in the data members name, age and salary. Here this has been used to store data since it CONTAINS the address of the current object. The function show( ) has been used to display the data of employee. |
|