I didn't overload the (=
) operator but still it runs fine in codeblocks. however when I ran this code on C++ shell it compiled successfully however the output was blank. Can somebody please explain why is it running fine in codeblocks even though I didn't write the code for the copy assignment?
Also another question...
If on line 1 I change the return type to string
instead of string&
it displays an error (about temporary variable) but if I change the code of line 2 to dummy(dummy& abc : ptr(new string (abc.print()))
the program runs fine (despite the return type of line 1 being string
). Why is it so?
class dummy {
string* ptr;
public:
dummy(string ab) {
ptr = new string;
ptr = &ab;
}
~dummy() { delete ptr; }
string& print() { return *ptr; } // line1
dummy(dummy& abc) {
ptr = new string;
ptr = &(abc.print());
} // line2
dummy(){};
};
int main() {
dummy x("manzar");
dummy y;
y = x;
cout << x.print();
cout << "\n" << y.print();
}
I didn't expect it to run fine however it is working fine. It is copying the content from x
to y
.