Possible Duplicate:
What is The Rule of Three?
The following code outputs garbage at best or crashes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class C {
public:
char* s;
C(char* s_) {
s=(char *)calloc(strlen(s_)+1,1);
strcpy(s,s_);
};
~C() {
free(s);
};
};
void func(C c) {};
void main() {
C o="hello";
printf("hello: %s\n",o.s); // works ok
func(o);
printf("hello: %s\n",o.s); // outputs garbage
};
I really wonder why – the object should not even be touched because Im passing it by value …
everthing about your code is bad in the eyes of C++, sorry.
try this
In this example you don’t have to worry about memory allocation and destruction, printf format strings or strcpy. It is much more robust.
C with classes (which is what you are writing) is categorically wrong, and blindly ignores the features that were created to make the language safer and easier without overhead.