3i Infotech Placement: Sample Questions 310 - 310 of 1245

Glide to success with Doorsteptutor material for competitive exams : get questions, notes, tests, video lectures and more- for all subjects of your exam.

Question 310

Edit

Describe in Detail

Essay▾

What is the output of following program:

  1. classSample
  2. {
  3.     public:
  4.     int ⚹ptr;
  5.     Sample (inti)
  6.     {
  7.         ptr =newint (i);
  8.     }
  9.     ~Sample ()
  10.     {
  11.         deleteptr;
  12.     }
  13.     voidPrintVal ()
  14.     {
  15.         cout ≪ “Thevalueis” ≪ ⚹ptr;
  16.     }
  17. };
  18. voidSomeFunc (Samplex)
  19. {
  20.     cout ≪ “SayiaminsomeFunc” ≪ endl;
  21. }
  22. intmain ()
  23. {
  24.     Samples1 =10;
  25.     SomeFunc (s1);
  26.     s1. PrintVal ();
  27. }

Explanation

  • In the program
Table Showing the Program
  1. classSample
  2. {
  3.     public:
  4.     int ⚹ptr;
  • Define the sample class
  • int ⚹ ptr; defines the integer pointer ptr
  1. Sample (inti)
  2. {
  3.     ptr =newint (i);
  4. }
  • defines the sample () function with integer parameters
  • ptr is assigned the integer parameter i
  1. ~Sample ()
  2. {
  3.     deleteptr;
  4. }
  • define the ~sample () function
  • deletes the ptr pointer
  1. voidPrintVal ()
  2. {
  3.     cout ≪ “Thevalueis” ≪ ⚹ptr;
  4. }
  • define the printval () function
  • cout prints the ⚹ ptr value
  1. voidSomeFunc (Samplex)
  2. {
  3.     cout ≪ “SayiaminsomeFunc” ≪ endl;
  4. }
  • define the SomeFunc () function
  • Cout prints “Say i am in someFunc”
  1. intmain ()
  2. {
  3.     Samples1 =10;
  4.     SomeFunc (s1);
  5.     s1. PrintVal ();
  6. }
  • Define the sample () function s1 = 10
  • S1 value pass in SomeFunc () function
  • Printval () function use the s1 value
  • As the object is passed by value to SomeFunc the destructor of the object is called when the control returns from the function.
  • So when PrintVal is called it meets up with ptr that has been freed.
  • The solution is to pass the Sample object by reference to SomeFunc: void SomeFunc (Sample &x) {cout << “Say i am in someFunc” << endl;} because when we pass objects by reference that object is not destroyed while returning from the function.

Developed by: