Created
August 13, 2014 08:10
-
-
Save lgp171188/34905055716a05f28a42 to your computer and use it in GitHub Desktop.
Illustration of deep copy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
class A | |
{ | |
public: | |
int x; | |
A(int v):x(v) {} | |
}; | |
class B | |
{ | |
public: | |
A * aref; | |
B (A* a) { | |
this->aref= a; | |
} | |
B(const B& B1) { | |
if (B1.aref) { | |
aref = new A(B1.aref->x); | |
} | |
else | |
aref = NULL; | |
} | |
B& operator=(const B& B1) { | |
if (this == &B1) | |
return *this; | |
if (B1.aref) { | |
aref = new A(B1.aref->x); | |
} | |
else | |
aref = NULL; | |
} | |
friend ostream& operator<<(ostream& cout, const B& b1) | |
{ | |
cout<<"address of B object:"<<&b1<<endl; | |
cout<<"aref of B object:"<<b1.aref<<endl; | |
cout<<"aref->x of B object:"<<b1.aref->x<<endl; | |
} | |
}; | |
int main() | |
{ | |
A a(15); | |
B b(&a); | |
B c(b); | |
B d = c; | |
cout<<"a"<<endl; | |
cout<<&a<<" "<<a.x<<endl; | |
cout<<"b"<<endl; | |
cout<<b; | |
cout<<"c"<<endl; | |
cout<<c; | |
cout<<"d"<<endl; | |
cout<<d; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment