In writing a copy constructor for a class that holds a pointer to dynamically allocated memory, I have a question.
How can I specify that I want the value of the pointer
I assume your class looks like this.
class Bar {
Foo* foo;
...
}
In order to do a deep copy, you need to create a copy of the object referenced by 'bar.foo'. In C++ you do this just by using the new
operator to invoke class Foo's copy constructor:
Bar(const Bar & bar)
{
this.foo = new Foo(*(bar.foo));
}
Note: this solution delegates the decision of whether the copy constructor new Foo(constFoo &) also does a 'deep copy' to the implementation of the Foo class... for simplicity we assume it does the 'right thing'!
[Note... the question as written is very confusing - it asks for the 'value of the pointer of the copied from object' that doesn't sound like a deep copy to me: that sounds like a shallow copy, i.e. this.
Bar(const Bar & bar)
{
this.foo = bar.foo;
}
I assume this is just innocent confusion on the part of the asker, and a deep copy is what is wanted.]