What will be printed out as a result of the following code execution?

#include <iostream>

using namespace std;

class A {
    friend A &operator+(A &, const int);
    int getValue() const;
    int val;

A::A() { val = 0; }

int A::getValue() const { return val; }

A &operator+ (A &sa, const int a) {
    sa.val += a;
    return sa;

int main(void) {
  A q, w;
  w + 3;  // 1
  q = q + 2;  // 2
  w = w + q.getValue();  // 3
  cout << q.getValue() << w.getValue();
  return 0;
There is no error in line 1- there is an overloaded addition operator in the class that "knows" how to operate with integer values.
There is no error in line 2, since the compiler will generate and use the assignment operator by default.
There is no error in line 3 as well since the public getValue() method returns an integer result, therefore an overloaded addition operator will be applied here again.

@hrendashtam23 checked here: https://ideone.com/BhCH3Z . Looks fine so far

2017 Dec 1, 6:25:16 PM

Isn't A:: needed in this line? A &operator+ (A &sa, const int a) {

2017 Nov 19, 7:32:57 AM

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback