Mar 5, 2013 at 1:20am UTC
remove && c.name[i] on line 6 and you need to declare hobby and weight
Mar 5, 2013 at 2:13am UTC
The code is part of a program... This is the class members,
// char name[20];
// char * hobby;
// double weight;
I use new in my constructor, I don't see why this doesn't work!
Mar 5, 2013 at 2:36am UTC
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.
Mar 5, 2013 at 2:43am UTC
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.
Mar 5, 2013 at 4:03am UTC
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
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 Mar 5, 2013 at 4:04am UTC
Mar 5, 2013 at 4:32am UTC
I don't see a problem with this ctor. The problem must be elsewhere.
Mar 5, 2013 at 4:46am UTC
anything wrong with this code?:
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
Cow var;
Cow var2("cow" , "running" , 393.8);
var.ShowCow();
var2.ShowCow();
var = var2;
var.ShowCow();
std::cin.get();
return 0;
}
Last edited on Mar 5, 2013 at 6:41am UTC
Mar 5, 2013 at 5:24am UTC
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.
Mar 5, 2013 at 5:42am UTC
I can confirm that it didn't solve the problem. But yea, it also looks wrong to me when I think about it.
Mar 5, 2013 at 10:52am UTC
You dereference `hobby' being NULL.