ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Account {
double balance;
public:
Account(double b) : balance(b) {}
Account operator+(const Account &other) const {
return Account(balance + other.balance);
}
double get() const { return balance; }
};
int main() {
Account a(100), b(50);
Account c = a + b;
cout << c.get();
}- A. 100
- B. 50
- C. 150
- D. Compile-time error: operator+ must be a free function, not a member
Correct answer: C. 150
operator+ is declared as a member function taking one parameter (the right-hand operand); a + b calls a.operator+(b), which is perfectly legal — binary operators may be overloaded either as members (with the left operand as the implicit *this) or as free functions. It returns a new Account with balance 100+50=150.
More OOP with C++ and Java questions
- What is printed? java class Base { public static void greet() { System.out.print("Base.greet "); } } class Sub extends Base { public…
- What is printed? cpp struct Base { void greet() { cout << "Base::greet "; } }; struct Sub : Base { void greet() { cout << "Sub::greet "; }…
- What is printed? cpp struct Base { static void hello() { cout << "Base::hello "; } }; struct Derived : Base { static void hello() { cout…
- What is printed? java class Outer { static int x = 100; static class Nested { int x = 200; void show() { System.out.println(x + " " +…
- What is printed? cpp class Singleton { static Singleton instance; Singleton() { cout << "Created "; } public: static Singleton get() { if…
- What is printed? cpp struct Base { int level = 1; }; struct Mid : Base { int level = 2; }; struct Leaf : Mid { int level = 3; void show()…