hey i am trying to understand how to overload the operator= when there is an inheritance
with no Success.
code example:
class Person
{
private:
char* m_name;
char* m_lastName;
.....
public:
virtual Person& operator=(const Person& other);
};
/********************/
cpp implementation
/********************/
#include "Person.h"
Person& Person:: operator=(const Person& other)
{
if(this == &other)
return *this;
delete[] m_name;
delete[] m_lastName;
if (other.m_name!=NULL)
{
m_name = new char[strlen (other.m_name)+1];
strcpy(m_name,other.m_name);
}
if (other.m_lastName!=NULL)
{
m_lastName = new char[strlen (other.m_lastName)+1];
strcpy(m_lastName,other.m_lastName);
}
return (*this);
}
now lets say Student inherit from Person how should the = operator should be implemented
i think it should be like the following please correct me cause i am probably being wrong:
#include "Person.h"
class Student : public Person
{
private:
char* m_collageName;
.....
public:
virtual Person& operator=(const Person& other);
};
/********************/
cpp implementation
/********************/
#include "Student.h"
Person& Student:: operator=(const Person& other)
{
if(this == &other)
return *this;
Person::operator=(other);
delete[] m_collage;
if ((Student)other.m_collageName != NULL)
{
m_collageName = new char[strlen((Student)other.m_collageName)+1];
strcpy(m_collageName,(Student)other.m_collageName);
}
return (*this);
}
Thanks alot in advance much appriciate it.
Your implementation is not typesafe, because I can write:
And it will compile the assignment successfully, but will result in U.B. (likely segfault or garbage read) at runtime, because you downcast the right argument of
operator=fromPersontoStudent, while it is not one.More generally, a virtual assignment operator doesn’t really make sense, since you’ll have to define assignment from
Person(rather than a specific subclass) in all derived classes, and it is very unlikely that it is a meaningful operation for them.