The program below crashes anytime I run it, can anyone tell what I have done wrong?.

#include <iostream>
#include <cstring>
using namespace std;

class Human
{
	private:
		char *fname;
		char *srname;
		char *phone;
	
	public:
		char * getFirstName();
		char * getLastName();
		char * getPhone();
		Human(char *fn, char *sn, char *ph);
		~Human();
		Human(const Human &hm);
};

void showDetails(Human person)
{
	cout<<"----DETAILS----"<<endl;
	cout<<"FIRST NAME : "<<person.getFirstName()<<endl;
	cout<<"SURNAME : "<<person.getLastName()<<endl;
	cout<<"PHONE : "<<person.getPhone()<<endl;
}

int main()
{
	Human man("Kofi", "Johnson", "0945166874");
	showDetails(man);
	return 0;
}

Human::Human(char *fn, char *sn, char *ph)
{	
	fname = new char[strlen(fn) + 1];
	srname = new char[strlen(sn) + 1];
	phone = new char[strlen(ph) + 1];
	
	strcpy(fname, fn);
	strcpy(srname, sn);
	strcpy(phone, ph);
}

Human::~Human()
{
	delete fname;
	delete srname;
	delete phone;
	cout<<"Destructor called."<<endl;
}

Human::Human(const Human &hm)
{
	char *copy_fname, *copy_srname, *copy_phone;
	copy_fname = new char[strlen(hm.fname) + 1];
	copy_srname = new char[strlen(hm.srname) + 1];
	copy_phone = new char[strlen(hm.phone) + 1];
	
	strcpy(copy_fname, hm.fname);
	strcpy(copy_srname, hm.srname);
	strcpy(copy_phone, hm.phone);
}

char * Human::getFirstName()
{
	return fname;
}

char * Human::getLastName()
{
	return srname;
}

char * Human::getPhone()
{
	return phone;
}

Windows reports that the program has encountered a problem anytime I run it.

Windows reports that the program has encountered a problem anytime I run it.

That's a generic error. You'll need something a little more specific. What's the output before it crashes? Anything?

The program compiles without any error, but this is what I get anytime I run it.

Edited 5 Years Ago by cossay: n/a

Two problems.

1. showDetails is designed so that it makes an unneeded call to the copy constructor. Stick an & in there.
2. Problem in the copy constructor. You're copying to local variables that go out of scope rather than the class variables.

And in the destructor:

Human::~Human()
{
	fname = 0;
	delete fname;
	srname = 0;
	delete srname;
	phone = 0;
	delete phone;
	cout<<"Destructor called."<<endl;
}

It is more secure to set the pointers to null.

Sorry:

Human::~Human()
      {
      delete fname;
      fname = 0;
      delete srname;
      srname = 0;
      delete phone;
      phone = 0;
      cout<<"Destructor called."<<endl;
      }
This question has already been answered. Start a new discussion instead.