remove && c.name[i] on line 6 and you need to declare hobby and weight
The code is part of a program... This is the class members,
// char name;
// char * hobby;
// double weight;
I use new in my constructor, I don't see why this doesn't work!
Is there any reason why name & hobby are an array of char and not a std::string?
That would make things a lot easier wouldn't it?
Why do you have a copy assignment operator anyway? It does not seem to do anything different to the implicit default one.
The default would just copy the address instead of copying the contents... And it is a programming exercise, can't use string, that would be cheating.
The only obvious problem I see with your operator= is that it will fail miserably for self assignment. Another caveat is that it isn't exception safe.
I would expect something more like:
Cow& Cow::operator=(const Cow& c)
using std::strlen ;
if ( &c != this )
if ( strlen(hobby) < strlen(c.hobby) ) // attempt memory allocation before making any changes.
char * mem ;
mem = new char[strlen(c.hobby)+1] ;
delete  hobby ;
hobby = mem ;
std::copy(c.name, c.name+strlen(c.name)+1, name) ;
std::copy(c.hobby, c.hobby+strlen(c.hobby)+1, hobby) ;
return *this ;
But I suspect your problem lies elsewhere.
Last edited on
I don't see a problem with this ctor. The problem must be elsewhere.
anything wrong with this code?:
Cow var2("cow", "running", 393.8);
var = var2;
Last edited on
name[strlen(name + 1)] = '\0';
That is certainly wrong.. and completely unnecessary, although I doubt it's the cause of your problems. The chief suspect at this point is your default constructor.
I can confirm that it didn't solve the problem. But yea, it also looks wrong to me when I think about it.
You dereference `hobby' being NULL.