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

C & C Plus Plus
Edit

Write in Short

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

Explanation

• In a 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

C & C Plus Plus
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
 class Sample{    public:    int ⚹ptr; Define the sample classint ⚹ ptr; defines the integer pointer ptr Sample (int i){    ptr =new int (i);} defines the sample () function with integer parametersptr is assigned the integer parameter i ~Sample (){    delete ptr;} define the ~sample () functiondeletes the ptr pointer void PrintVal (){    cout ≪ “The value is” ≪ ⚹ptr;} define the printval () functioncout prints the ⚹ ptr value void SomeFunc (Sample x){    cout ≪ “Say i am in someFunc” ≪ endl;} define the SomeFunc () functionCout prints “Say i am in someFunc” int main (){    Sample s1 =10;    SomeFunc (s1);    s1. PrintVal ();} Define the sample () function s1 = 10S1 value pass in SomeFunc () functionPrintval () 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: