203k views
1 vote
Trace the output of the following code:

#include
using namespace std;

class A{
public:
int x, y, sum;
static int temp;
A()
{
this->x = 5;
this->y = 12;
this->sum = this->x + this->y - 3;
}
void methodA(int m, int n)
{
int x = m + n;
this->y = this->x + x + n;
this->x = this->sum + temp;
temp += 1;
this->sum = x + this->y + temp;
cout< y<<" "< sum;
}
};

class B: public A{
public:
int sum;
static int x;
B(){
this->sum = 22;
}
void methodB(int m, int n)
{
int y = 0;
y = y + this->y;
this->methodA(x, y);
x = A::temp + n + m;
this->sum = A::temp + this->y + y;
cout< y<<" "< sum< }
};
int A::temp = 3;
int B::x = 5;

//Driver Code
int main()
{
A a1;
B b1;
a1.methodA(2, 3);
b1.methodA(3, 2);
b1.methodB(5, 3);
return 0;
}

User Jpmarinier
by
7.9k points

1 Answer

1 vote

Based on the code given above, the final output of the code is:

16 43

28 99

19 123

0 130

What is the output of the code?

The C++ code in the question is one that creates instances of classes A and B, initializing their attributes. Methods method A and method B modify attributes based on input parameters and class inheritance.

Therefore, The output reveals the values of y and sum at different points in the program. Notably, method calls and updates cascade through the inheritance hierarchy. The final output displays the evolving values of y and sum during the execution of the program: 16 43, 28 99, 19 123, and 0 130.

User Kartlee
by
7.5k points