Languages-C & C Plus Plus [3i Infotech Placement]: Sample Questions 88 - 89 of 354

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

Question 88

Write in Short Short Answer▾

  1. main ()
  2. {
  3. int c =--2;
  4. printf ( “c =%d c);
  5. }
Edit

Explanation

  • In a program
    Table Shows the Program
    int c =-2;Here negation operator is used twice.

    Here apply maths rule: minus ⚹ minus = plus

    printf ( “c =% d” c) ;So, print “c = 2”
  • Note the key difference:- operator can only be applied to variables as decrement operator (e. g. i-) . 2 is constant and not a variable

Question 89

Describe in Detail Essay▾

What is the output of following program:

  1. class Sample
  2. {
  3. public:
  4. int ptr;
  5. Sample (int i)
  6. {
  7. ptr =new int (i);
  8. }
  9. ~Sample ()
  10. {
  11. delete ptr;
  12. }
  13. void PrintVal ()
  14. {
  15. cout ≪ “The value is” ≪ ⚹ptr;
  16. }
  17. };
  18. void SomeFunc (Sample x)
  19. {
  20. cout ≪ “Say i am in someFunc” ≪ endl;
  21. }
  22. int main ()
  23. {
  24. Sample s1 =10;
  25. SomeFunc (s1);
  26. s1. PrintVal ();
  27. }
Edit

Explanation

  • In the program
Table Showing the Program
  1. class Sample
  2. {
  3. public:
  4. int ptr;
  • Define the sample class
  • int ⚹ ptr; defines the integer pointer ptr
  1. Sample (int i)
  2. {
  3. ptr =new int (i);
  4. }
  • defines the sample () function with integer parameters
  • ptr is assigned the integer parameter i
  1. ~Sample ()
  2. {
  3. delete ptr;
  4. }
  • define the ~sample () function
  • deletes the ptr pointer
  1. void PrintVal ()
  2. {
  3. cout << “The value is” << ⚹ptr;
  4. }
  • define the printval () function
  • cout prints the ⚹ ptr value
  1. void SomeFunc (Sample x)
  2. {
  3. cout << “Say i am in someFunc” << endl;
  4. }
  • define the SomeFunc () function
  • Cout prints “Say i am in someFunc”
  1. int main ()
  2. {
  3. Sample s1 =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.