Explain each line in main (you can put it in the comments) and explain why the output looks how it looks.
#include <iostream>
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;
};
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();
}
Greetings!!
int main()
{
A a; //create object a with initial value 0
A b(2); //create object b with initial value 2
A c=b; //create object c with initial value 2 ie the value of b is
assigned to c
A d=A(3);//create object d with initial value 3
a.f(); //call function f which increment parameter 0 to 1
b.g(); //call function g which call f() ie n=3 then n=n*2 ie n=6
then f() ie 7
c.f(); // =incremented to 3
d.g(); //f() ie n=4 then n=n*2 ie n=8 then f() ie 9
d.p(); //prints 9
A e(a.k() + b.k() + c.k() + d.k()); //sum of 1+7+3+9=20
e.p(); //prints 20
return 0;
}
Output screenshot:
Hope this helps
Get Answers For Free
Most questions answered within 1 hours.