This class-based program uses virtual memory in the driver routine and implementation routines. If I add a static char array by the instructors request, I keep getting execution errors, but it does compile okay.
I am just trying to get the name to print and continue before moving on. It does print the name as requested but crashes once the destructors are called. Commenting out the destructors seems to work but that is not a solution.
If I remove the static char array and just print a last name, it works fine with no errors but something with the strcat function and the destructors is possibly causing a memory problem.
Error:
Unhandled exception at 0x77f767cd in program3.exe: User breakpoint.
Code:
//*************** Person.h (Class Header)
class Person {
public:
Person ();
~Person();
Person (char*, char*, char*, char*, char*, char*);
const char* GetFullName () const;
virtual void Print ();
protected:
static char* fullName;
char* firstName;
char* LastName;
(other code omitted)
} // end of class header
// ************ Person.cpp (Class Implementation)
Person::~Person()
{
// works if fullName function removed and fullName function works if this removed?
delete [] FirstName;
delete [] LastName;
}
char* Person::fullName = 0; //Initialize static char array
Person::Person (char* first, char* last.......)
{ SetName (first, last); }
void Person::SetName (char* first, char* last)
FirstName = new char [strlen (first) + 1];
LastName = new char [strlen (last) + 1];
strcpy (FirstName, first);
strcpy (LastName, last);
// If these are removed, it works but then I have no way of retrieving the full name.
fullName = strcat (FirstName, " ");
fullName = strcat (fullName, LastName);
}
const char* Person::GetFullName () const {return fullName; }
void Person::Print () { cout << GetfullName(); }
// End of Person.cpp
// ************** School.cpp (Driver)
int main ()
{
Person *p2 = new Person ("Dave", "Walters", "1000 Street", "City", State", "Zip");
p2->Print ();
// works if fullName function removed and fullName function works if this removed?
delete p2;
p2 = 0;
} // end of driver main