ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class Account {
double balance;
public:
explicit Account(double b) : balance(b) {}
double get() const { return balance; }
};
void deposit(Account acc) { cout << acc.get(); }
int main() {
deposit(Account(100));
deposit(100);
}- A. 100100
- B. Compile-time error only on deposit(100): explicit blocks the implicit double-to-Account conversion needed here
- C. Compile-time error on both calls
- D. 100 then undefined behaviour
Correct answer: B. Compile-time error only on deposit(100): explicit blocks the implicit double-to-Account conversion needed here
explicit disables using the single-argument constructor for implicit conversions. deposit(Account(100)) explicitly constructs an Account, which is fine. deposit(100) tries to implicitly convert the int/double 100 into an Account to match the parameter type, which explicit forbids, so only that call fails to compile.
More OOP with C++ and Java questions
- What is printed? java class Base { protected Object clone2() { return new Base(); } } class Sub extends Base { @Override public Object…
- What is printed? java class Shape { double area() { return 0.0; } } class Rectangle extends Shape { double w, h; Rectangle(double w…
- What is printed? java class Vehicle implements Comparable<Vehicle> { int speed; Vehicle(int s) { speed = s; } public int compareTo(Vehicle…
- What is printed? cpp struct Base { virtual Base& self() { cout << "Base::self "; return this; } }; struct Derived : Base { Derived& self()…
- What is printed? java enum Status { ACTIVE, INACTIVE, BANNED; boolean isUsable() { return this == ACTIVE; } } public class Main { public…
- What happens when this is compiled? java enum Operation { ADD { public int apply(int a, int b) { return a + b; } }, MULTIPLY { public int…