InterviewSolution
Saved Bookmarks
| 1. |
Why Does The Following Code Fail? #include<iostream.> #include<string.h> Class Sample { Private :char *str ; Public : Sample ( Char *s ) { Strcpy ( Str, S ) ; } ~sample( ) { Delete Str ; } } ; Void Main( ) { Sample S1 ( "abc" ) ; } |
|
Answer» Here, through the destructor we are trying to deal locate memory, which has been ALLOCATED statically. To REMOVE an EXCEPTION, add following statement to the constructor. sample ( char *s ) { str = new char[strlen(s) + 1] ; strcpy ( str, s ) ; }Here, FIRST we have allocated memory of required size, which then would get deal LOCATED through the destructor. Here, through the destructor we are trying to deal locate memory, which has been allocated statically. To remove an exception, add following statement to the constructor. Here, first we have allocated memory of required size, which then would get deal located through the destructor. |
|