ASAPInfosystemsPvtLtd Interview Question
Software Engineer / DevelopersTeam: SoftwareDevelopment
Country: India
Hi, you need to take care of assigning an object to itself, like
a = a;
A& A::operator=(const A& other)
{
if(&other == this) return *this;
if (other.name) {
size_t n = strlen(other.name) + 1;
delete [] this->name; // also delete this-> name to avoid memory leak
this->name = new char[n];
strncpy(this->name, other.name, n);
}
return *this;
}
Yes, you are absolutely right - this was a 2 minutes sketch during a lunch break. There is also a problem when other.name is null in the code - this.name always needs deleting.
A& A::operator=(const A& other)
{
if (&other != this) {
delete [] this->name;
if (other.name) {
size_t n = strlen(other.name) + 1;
this->name = new char[n];
strncpy(this->name, other.name, n);
}
}
return *this;
}
Think it'd be fair feedback in the interview to point out that using C++ allocators with C strings is awkward, ie can't use strdup. There's also been a std::string class for 20 years that'd avoid :-)
Implement copy constructor and operator= to perform a deep copy of the name field, e.g.
- MrZipf December 16, 2014