J
john
Hey,
I know we use the pointer this to obtain a class object or class
member data. I don't follow the reason for example this code. I'am
quite confused
assingment operator
const B &operator=(const B& x){
if (&x != this)
a = x.a;
else
return *this;
}
This is how i see this code. its compares the reference of x to the
adress of the this pointer??
In a line like this, i don't follow the steps the compiler takes.
b1 = b2;
Code below
---------------------------------------------------------------------
#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);
b1 = b2;
b1.print();
a1.good();
}
cout << endl;
int trick;
cin >> trick;
return 0;
}
//--------------------------------------------------------------------------------
thnak you
I know we use the pointer this to obtain a class object or class
member data. I don't follow the reason for example this code. I'am
quite confused
assingment operator
const B &operator=(const B& x){
if (&x != this)
a = x.a;
else
return *this;
}
This is how i see this code. its compares the reference of x to the
adress of the this pointer??
In a line like this, i don't follow the steps the compiler takes.
b1 = b2;
Code below
---------------------------------------------------------------------
#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);
b1 = b2;
b1.print();
a1.good();
}
cout << endl;
int trick;
cin >> trick;
return 0;
}
//--------------------------------------------------------------------------------
thnak you