Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Who can help me explain about the output and each line in mainThanks #include \"

ID: 3816991 • Letter: W

Question

Who can help me explain about the output and each line in mainThanks

#include "iostream.h"
#include "stdlib.h"
class A
{
public:
       A()
       {
              n=0;
       }
       A(int x)
       {
              n=x;
       }
       void f()
       {
              n++;
       }
       void g()
       {
              f();
              n=n*2;
              f();
       }
       int k()
       {
              return n;
       }
       void p()
       {
              cout<<n<<endl;
       }
private:
       int n;
};
void main()
{
       A a;
       A b(2);
       A c=b;
       A d=A(3);
       a.f();
       b.g();
       c.f();
       d.g();
       d.p();
       A e(a.k() + b.k() + c.k() + d.k());
       e.p();
}

Explanation / Answer

#include <iostream>
#include <stdlib.h>

using namespace std;

class A
{
public:
A()
{
n=0;
}
A(int x)
{
n=x;
}
void f()
{
n++;
}
void g()
{
f();
n=n*2;
f();
}
int k()
{
return n;
}
void p()
{
cout<<n<<endl;
}
private:
int n;
};
int main()
{
A a;   // Declare a of type A, here n =0;
A b(2); // Declare b of type A by calling the constructor passing integer 2, hence n=2
A c=b; // reference variable c now refer to b; hence n=2
A d=A(3); // Declare d of type A by calling the constructor passing integer 3, hence n=3
a.f(); // invoke the method f() with the reference variable a, hence n=1
b.g(); // invoke the method g() with the reference variable b, internally calls f, make n=3,then n=3*2==6, then again calls f(), hence n=7
c.f(); // invoke the method f() with the reference variable c, hence n=3
d.g(); // invoke the method g() with the reference variable d, internally calls f, make n=4,then n=3*2==8, then again calls f(), hence n=9
d.p();// invoke the method to print the value of n for d, prints 9
A e(a.k() + b.k() + c.k() + d.k());// calls first for a.k() + b.k() + c.k() + d.k() --> 1+7+3+9=20, hence n=20
e.p();// invoke the method to print the value of n for e, prints 20
return 0;
}


--------------output--------------
9
20
---------------output--------------

Note: Feel free to ask any question in case of any doubts. God bless you!!