D

Dharmendra Sir • 3.53K Points
Extraordinary

Q. What is the output of the following C++ code?

Code:
#include<iostream> 
using namespace std; 
 
class A {
 private: 
    int val;   
 public: 
    A(int v = 0) : val(v) {} 
    void display() { cout << "val = " << val << endl;} 
}; 
 
class B { 
 private: 
    int val; 
 public: 
    B(int v) : val(v) {} 
    operator A() const { return A(val); } 
}; 
 
void f(A a) 
{  a.display(); } 
 
int main() { 
  B b(5); 
  f(b); 
  f(55); 
  return 0; 
}
  • (A) val = 5 and val = 5
  • (B) val = 5 and val = 55
  • (C) val = 5
  • (D) val = 55
  • Correct Answer - Option(B)
  • Views: 105
  • Filed under category C++

Explanation by: Dharmendra Sir
Since there is a conversion constructor in class A, an integer value can be assigned to objects of class A and the function call f(55) works correctly. In addition, there is an overloaded conversion operator in class B, so we can call f() with objects of class B.

You must be Logged in to update hint/solution

Discusssion

Login to discuss.

Be the first to start discuss.


Question analytics