T
Tony Johansson
Hello!
Assume I have the following two classes Student and InfoStudent and its
definition below.
In the definition of the assignment operator that is defined I can remove
these two lines
if (this == &s)
return *this;
when I have done this is main which is assign to myself
InfoStudent is(1);
is = is;
and it work just as good as with them. So what's the point having them?.
Here is my explanation why is works.
First the left side resouces is deleted here the Student object rep_
then a new student object pointer rep_ is created with new passing the
student number from the right operand s.
So why have this
if (this == &s)
return *this;
if it's work all the same without when I assign an object to my self as I
hade done with object is=is;
//Tony
Definition of assignment operator
*************************
InfoStudent& InfoStudent:perator=(const InfoStudent& s)
{
if (this == &s)
return *this;
delete rep_;
rep_ = new Student(s.number());
return *this;
}
class definitions
************
class Student
{
public:
Student(long);
void number(long);
long number() const;
private:
long number_;
};
class InfoStudent
{
public:
InfoStudent(long);
InfoStudent(const InfoStudent&);
~InfoStudent();
InfoStudent& operator=(const InfoStudent&);
long number() const;
private:
Student* rep_;
};
Assume I have the following two classes Student and InfoStudent and its
definition below.
In the definition of the assignment operator that is defined I can remove
these two lines
if (this == &s)
return *this;
when I have done this is main which is assign to myself
InfoStudent is(1);
is = is;
and it work just as good as with them. So what's the point having them?.
Here is my explanation why is works.
First the left side resouces is deleted here the Student object rep_
then a new student object pointer rep_ is created with new passing the
student number from the right operand s.
So why have this
if (this == &s)
return *this;
if it's work all the same without when I assign an object to my self as I
hade done with object is=is;
//Tony
Definition of assignment operator
*************************
InfoStudent& InfoStudent:perator=(const InfoStudent& s)
{
if (this == &s)
return *this;
delete rep_;
rep_ = new Student(s.number());
return *this;
}
class definitions
************
class Student
{
public:
Student(long);
void number(long);
long number() const;
private:
long number_;
};
class InfoStudent
{
public:
InfoStudent(long);
InfoStudent(const InfoStudent&);
~InfoStudent();
InfoStudent& operator=(const InfoStudent&);
long number() const;
private:
Student* rep_;
};