There is a lot of stuff wrong with this code, but I will list a few of the big ones.
- As smentioned by others, you
new char
's need to be one bigger than they are. - You default constructor should set name to nullptr.
- you have a memory handling error whenever you do an assignment, eg on this line:
drv = d;
because it calls the default operator=, which is incorrect in your case. Ther eis the Law of the Big Three which loosely states that whenever you need either a (non-trivial) copy constructor, copy assignment operator, or destructor, you'll most likely need to implement the others, too. You need to write an operator=!
Based on existing code, I would expect your operator= to look vaguely like this:
//assignment operator
const driver&operator=(const driver &rhs)
{
if (this==&rhs) return *this;
delete[] this->name;
this->name = new char[strlen(rhs.name)+1];
strcpy(this->name, rhs.name);
this->age = rhs.age;
return *this;
}
Do all that, and your core dump goes away.
PS Please, please just learn to use std::strings, new-ing char arrays and managing the memory yourself is a bad bad move.