overloading the = operator with inheritance
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 followin开发者_JAVA技巧g 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.
A virtual
assignment operator seems an abomination to me. Assignment is for value types, while virtual
is for polymorphic types. And these two are pretty much on opposite ends of the spectrum.
Imagine, for a while, this code:
void foo(person& x, const person& y)
{
x = y;
}
plus we're having this
class teacher : public person {...};
class student : public person {...};
and now we're calling this as:
teacher t;
student s;
foo(s,t);
What should that do? Turn a student into a teacher? How so?
Your implementation is not typesafe, because I can write:
Student s;
Person p;
s = p;
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=
from Person
to Student
, 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.
精彩评论