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;
}
β
Correct Answer: (B)
val = 5 and val = 55
Explanation: 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.