#include <iostream>
#include <cstring>

using namespace std;

class Cow
{
	char name[20];
	char * hobby;
	double weight;
	public:
		Cow()
		{
			strcpy(name,"peter");
			strcpy(hobby,"nothing");
			weight = 1.0;
		}

		Cow(const char * nm, const char * ho, double wt)
		{
			int len = strlen(ho);
			strncpy(name,nm,19);
			name[19] = '\0';
			hobby = new char[len + 1];
			strcpy(hobby,ho);
			weight = wt;
		}

		Cow(const Cow & c)
		{
			int len = strlen(c.hobby);
			strcpy(name,c.name);
			hobby = new char[len + 1];
			strcpy(hobby,c.hobby);
			weight = c.weight;
		}

		~Cow()
		{
			delete [] hobby;
		}

		Cow & operator=(const Cow & c)
		{
			strcpy(name,c.name);
			delete [] hobby;
			hobby = new char[strlen(c.hobby) + 1];
			strcpy(hobby,c.hobby);
			weight = c.weight;
        }

		void ShowCow() const
		{
			cout << "Name: " << name << endl
				<< "Hobby: " << hobby << endl
				<< "Weight: " << weight << endl;
		}
};

int main()
{
    Cow cow1;
    cow1.ShowCow();

    return 0;
}

Program just crashes, spent time on it, but can't seem to find the problem. Does anyone see the problem?

Use a debugger (or pepper it with cout statements) to see how far it gets in execution. If you can't find it after that, post back and I'll compile it.

Ohhh, I actually got it myself! I just used the new keyword for hobby above line 15 and it worked. Anyone know why it's necessary to do this? Won't strcpy() copy the address of the first letter of the string to the hobby pointer, making it an array of char (and adding an addition null character since that's what strcpy() does).

Also, does strcpy() overwrite the contents in the destination string, or does it continue to add onto it?

Won't strcpy() copy the address of the first letter of the string to the hobby pointer,

The compiler knows that hobby is a pointer, but there's no space allocated, so it's not pointing to anything.

strcpy won't keep adding on.

This question has already been answered. Start a new discussion instead.