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
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:
class Sample
{
public:
int ⚹ptr;
Sample (int i)
{
ptr =new int (i);
}
~Sample ()
{
delete ptr;
}
void PrintVal ()
{
cout ≪ “The value is” ≪ ⚹ptr;
}
};
void SomeFunc (Sample x)
{
cout ≪ “Say i am in someFunc” ≪ endl;
}
int main ()
{
Sample s1 =10;
SomeFunc (s1);
s1. PrintVal ();
}
Explanation
- In the program
|
|
|
|
|
|
|
|
|
|
|
|
- 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.