Checking assignment operators with *this pointer

J

john

Hey,

I'am confused on the principles on checking a assingment operators
using This pointer. I understand using *this to access data member in
a class.

const B &operator=(const B& x){

if (&x != this)
a = x.a;

else
return *this;
}


What i don't understand is the fact In this code i'am comparing &x
reference to the this pointer which i'am not sure what it is
containing or how it is comparing.

b1 = b2; in this line of code is b1 the reference and comparing itself
with b2?

below is code


thanks
-----------------------------------------------------------------


#include <iostream>
using namespace std;


class A
{
int n ;

public:
A():n(0)
{
}
A(int x):n(x)
{
n = x;


}
A(A &c):n(){

n = c.n;
}


void print()
{ cout << n<<"\n\n";
}


A(const A& objectCopy){


n = objectCopy.n; // copy constructor


}
const A &operator=(const A x){
n = x.n; // Operator

}
void good(){
cout<< this->n<<"";
}

};


class B
{
A * a;

int v;

public:


B(A & x)
{


a = new A(x);


}


void print ()
{
a->print();
}
B(const B& copy){ // Class B copy constructor
a = copy.a;

}
const B &operator=(const B& x){


if (&x != this)
a = x.a;


else
return *this;



// return *this;
//delete a;
}
B::~B(){
delete a;


}

};


//-------------------------------------------------------------------------­--

int main()
{

{

A a1(5);
A a2(7);
B b1(a2);
b1.print();
B b2(a1);
b2.print();
b1 = b2;
b1.print();



//a1.good();



}



cout << endl;
int trick;
cin >> trick;
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top