πŸ“Š C++
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
πŸ’¬ Discuss
βœ… 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.

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.

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
200
Total Visits
πŸ“½οΈ
4 y ago
Published
πŸŽ–οΈ
Dharmendra Sir
Publisher
πŸ“ˆ
83%
Success Rate