Fix the Compilation Error and find the output
#include<iostream>
using namespace std;
class Test
{
int x;
public:
Test(int x=0)
{
this->x=x;
}
void change(Test *t)
{
this=t;
}
void print()
{
cout<<"x="<<x<<endl;
}
};
int main()
{
Test obj(5);
Test *ptr=new Test(10);
obj.change(ptr);
obj.print();
return 0;
}
Error
value required as left operand of assignment
Fix:
#include<iostream>
using namespace std;
class Test
{
int x;
public:
Test(int x=0)
{
this->x=x;
}
void change(Test *t)
{
this->x=t->x;
}
void print()
{
cout<<"x="<<x<<endl;
}
};
int main()
{
Test obj(5);
Test *ptr=new Test(10);
obj.change(ptr);
obj.print();
return 0;
}
#include<iostream>
using namespace std;
class Test
{
int x;
public:
Test(int x=0)
{
this->x=x;
}
void change(Test *t)
{
this=t;
}
void print()
{
cout<<"x="<<x<<endl;
}
};
int main()
{
Test obj(5);
Test *ptr=new Test(10);
obj.change(ptr);
obj.print();
return 0;
}
Error
value required as left operand of assignment
Fix:
#include<iostream>
using namespace std;
class Test
{
int x;
public:
Test(int x=0)
{
this->x=x;
}
void change(Test *t)
{
this->x=t->x;
}
void print()
{
cout<<"x="<<x<<endl;
}
};
int main()
{
Test obj(5);
Test *ptr=new Test(10);
obj.change(ptr);
obj.print();
return 0;
}
Output:
x=10