Ok is this one now correct??
Code:class str { char *s; public: str(){} ~str() { delete []s; } str(str &p) { s=new char[strlen(p.s)+1]; strcpy(s,p.s); } void getdata(char*); void putdata(); friend int xstrlen(str); };
Ok is this one now correct??
Code:class str { char *s; public: str(){} ~str() { delete []s; } str(str &p) { s=new char[strlen(p.s)+1]; strcpy(s,p.s); } void getdata(char*); void putdata(); friend int xstrlen(str); };
Looks good to me.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Ok last and final question..is what i am doing in this function is that i am allocating a new memory space for my string so that the "string" and *s point to different memory location so when the destructor frees the memory the original object doesn't get destroyed?
is this correct what i have understood?
Ok this is deep copying. Now what is shallow copying?that one which is there in getdata???right??
but in that also i allocated the memory so how come *s and "string" both point to the same location?
Shallow copy means you're just copying pointers over, while deep copy means you copy the data pointed to by the pointers, as well.
Huh? There is no "string." You forgot to give them a descriptive name.but in that also i allocated the memory so how come *s and "string" both point to the same location?
Oh, I also see something else. Always put names for arguments in class definitions, as well.
For example:
void getdata(char* pStr);
You mean the same 2 lines i have written in getdata and in copy constructor but still 1 is deep copy and 1 is shallow copy???
You mean the difference is just of the copy constructor??is it the root?
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
If both are deep copy then Elysia how come are they(object's pointer and the string) pointing to the same memory location?
Now you'll also need to overload the assignment operator. Otherwise you'll have the original problem when you do this:
Code:str a, b; a = b;
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
OK this time i got it for sure!! you mean to say when we do call by value for objects(xstrlen..in this case) the default copy constructor get's called and it copies only the address of the original object and doesn't allocate the memory?right??
and now what is anon talking about?why should be overload the assignment operator??the assignment operator is already overloaded isnt it??and i tried B=A as well as A=B but i am getting the right output only?