Languages-C & C Plus Plus [3i Infotech Placement]: Sample Questions 161 - 162 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 161

C & C Plus Plus
Edit

Write in Short

Short Answer▾

What is the output of the following program?

  1. main()
  2. {
  3.     inti =0;
  4.     while (+(+i--)! =0)
  5.     i=i ++;
  6.     printf (“%d”,i);
  7. }

Explanation

In the program

Table Shows the Program
int i = 0
  • Define the integer variable i = 0
while (+ (+ i-) ! = 0)
  • Unary + is the only dummy operator in C.
  • So it has no effect on the expression and now the while loop is:
  • While (+ (+ i-) ! = 0)

    i = 0

  • So 0! = 0 is false hence condition for while fails.
  • Now there is also a post decrement operator.
printf ( “% d” , i) ;
  • Value of i turns out to be -1. And that is which is printed.

Question 162

C & C Plus Plus
Edit

Describe in Detail

Essay▾

Which is the only operator in C ++ which can be overloaded but NOT inherited.

Explanation

  • The “=” (equal) operator can be overloaded but cannot be inherited.
  • Example:

#include < iostream > #include < iomanip > using namespace std; class A {public: int _i; A (int i) : _i (i) {} virtual A &operator = (A const &other) {if (this! = &other) {_i = other. _i;} return ⚹ this;} virtual A operator + (A const &rvalue) {return A (_i + rvalue. _i) ;} virtual void print () {cout << “A (_i =” << _i << “) ” ;} } ; class B: public A {public: int _j; B (int i, int j) : A (i) , _j (j) {} virtual void print () {cout << “B (_i =” << _i << “, _j =” << _j << “) ” ;} } ; int main () {A a1 (5) , a2 (3) ; a1. print () ; cout << “+” ; a2. print () ; cout << “=” ; A a3 = a1 + a2; a3. print () ; cout << endl; B b1 (5,3) , b2 (3,5) ; b1. print () ; cout << “+” ; b2. print () ; cout << “=” ; // this works, although (b1 + b2) returns an A since it uses A՚s operator + (b1 + b2) . print () ; // this does not work: no conversion from A to B, i.e.. operator = not inherited // B b3 = b1 + b2; // b3. print () ; cout << endl; return 0;}

Answer:

A (_i = 5) + A (_i = 3) = A (_i = 8)

B (_i = 5, _j = 3) + B (_i = 3, _j = 5) = A (_i = 8)

Developed by: