Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with implementing a program!!

Status
Not open for further replies.

chmilz

Programmer
Jan 10, 2001
94
CA
Hi,

I was recently testing a class that I had created and I can't figure out why it won't print the message that I want it to. The output of the program is supposed to be "Hello World" but when I run it, all I have is goop! Here is a copy of my code:

struct Dude
{
char * p;
Dude(); {p = new char[100]; strcpy(p, "Hello World");}

Dude(const Dude & dude)
{ p = new char [strlen(dude.p) + 1]; strcpy(p, x.p);}

Dude &operator=(const Dude & dude)
{ delete []p; p = new char[strlen(x.p)+1];
strcpy(p,x.p); return *this;}

~Dude() {delete []p;}
};

void bug(Dude & dude1, Dude &dude2)
{
dude1 = dude2;
}

int main()
{
Dude Man;
bug(Man, Man);
printf ("%s\n", Man.p);
return 0;
}

I cant seem to figure out what I did wrong. Any help is greatly appreciated!! Thank you!

 
hi,you should avoid the wrong deletion of original object
when override the '=' operator.

Dude &operator=(const Dude & dude)
{

if(this == &dude)
{
printf("avoid the same object\n");
return *this;
}

delete []p; p = new char[strlen(dude.p)+1];
strcpy(p,dude.p);
return *this;
}
 
try for helloworld.cpp

# include <iostream.h>

int main()

{
cout<< &quot;Hello World \n&quot;;
return 0;
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top