I have the below code for class A
class A
{
int *ptr;
public:
A();
A(const A &);
~A();
A& operator = (const A &);
void display();
};
void A::display()
{
cout<<" ptr ="<<*ptr<<endl;
}
A::A()
{
cout<<"A's constructor called"<<endl;
ptr = new int;
*ptr = 100;
}
A::A(const A &src)
{
cout<<"copy constructor called"<<endl;
ptr = new int;
*ptr = *src.ptr;
}
A::~A()
{
delete ptr;
cout<<" destructor called"<<endl;
}
A& A::operator = (const A &src)
{
cout<<"A::assignmnet operator called"<<endl;
if(&src != this)
{
delete ptr ;
ptr = new int;
*ptr = *src.ptr;
}
return *this;
}
Now there is another class B which contains a pointer to class A as a member variable
class B
{
A *a;
public:
B()
{
cout<<" B's constructor called"<<endl;
a = new A();
}
B& operator = (const B &);
~B()
{
cout<<"B:destructor called"<<endl;
delete a;
}
void display()
{
cout<<"inside B's display"<<endl;
a->display();
}
};
Now the assignment operator for class B can be written as 1.
B& B::operator=( const B & src)
{
cout<<"B's assignment operator called"<<endl;
if(this != &src)
{
*a = *src.a;
}
return *this;
}
Or as 2.
B& B::operator=( const B & src)
{
cout<<"B's assignment operator called"<<endl;
if(this != &src)
{
delete a;
a = new A();
*a = *src.a;
}
return *this;
}
Are these two scenario correct.
aa pointer when it's owned by the class?