ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Complex {
double re, im;
public:
Complex(double r, double i) : re(r), im(i) {}
Complex operator+(const Complex& o) const { return Complex(re + o.re, im + o.im); }
friend ostream& operator<<(ostream& os, const Complex& c) { return os << c.re << "+" << c.im << "i"; }
};
int main() {
Complex a(1, 2), b(3, 4);
cout << (a + b);
}- A. 4+6i
- B. Compilation error: operator+ must be a free function
- C. 1+2i3+4i
- D. Compilation error: operator<< cannot be a friend
Correct answer: A. 4+6i
operator+ is a member taking the other operand by reference, returning a new Complex(re+o.re, im+o.im) = Complex(4, 6). The friend operator<< then formats it as "4+6i" via the overloaded stream insertion.
More OOP with C++ and Java questions
- What is printed? java interface Calculator { int calculate(int a, int b); } public class Main { public static void main(String[] args) {…
- What is printed? java class Matrix { int[][] data; Matrix(int[][] d) { data = d; } Matrix add(Matrix other) { int[][] r = new…
- What is printed? java class Vehicle { private int speed; protected void setSpeed(int s) { speed = s; } int getSpeed() { return speed; } }…
- What is printed? cpp class Stack { vector<int> data; public: void push(int x) { data.pushback(x); } int pop() { int top = data.back()…
- What is printed? java interface Repository<T> { void save(T item); T find(int id); } class UserRepository implements Repository<String> {…
- What is printed? cpp class Printable { public: virtual void print() const = 0; virtual ~Printable() = default; }; class Report : public…