On Mon, 8 Jun 2015 16:54:10 -0700 (PDT), fl <
rxj...@gmail.com> wrote:
>Hi,
>
>I am still new to C++. When I read a post on-line, I do not understand one line:
>
>
>
>Fred(const Fred& f) : p_(new Wilma(*f.p_)) { }
>
>
>----------------------
>class Wilma { };
>class Fred {
>public:
> Fred() : p_(new Wilma()) { }
> Fred(const Fred& f) : p_(new Wilma(*f.p_)) { }
> ~Fred() { delete p_; }
>private:
> Wilma* p_;
>};
>-----------------------
>
>
>
>I know that f is a reference to a Fred object. *f.p_ is the pointer of object f. My question is about
Not quite. p_ is a private member of the class Fred. It has type
pointer to Wilma. f is a reference to a particular instance of the
class Fred. f.p_ is the pointer that is the member of that particular
instance. *f.p_ is the actual Wilma object that f.p_ points to.
>Wilma(*f.p_)
>
>or
>
>new Wilma(*f.p_)
>is class Wilma incomplete?
Given the code you have shown, yes. The declaration of Wilma on line
1 is a "forward declaration" whose only purpose is to allow p_ to be
defined. Since p_ is a pointer to a class, the compiler does not need
to know any of the internal specifics of that class before defining a
pointer to it. (All pointers to any class have the same size,
representation, and alignment requirements.)
Before you code can compile, someone must complete the declaration for
Wilma. Otherwise, any expression of the form "new Wilma" will
generate a diagnostic that the size of Wilma is not known.
>Please explain it to me if you can.
The copy constructor will only be called when you "execute" code
similar to:
Fred x;
Fred y(x);
When x is defined, the specified *default* constructor, Fred(),
executes. This constructor allocates space for a Wilma and stores the
address in x.p_. Whether the allocated space is initialized or
retains whatever residual data happened to be in memory depends on
Wilma's default constructor.
When y is defined, the specified *copy* constructor, Fred(const Fred&
f), executes. This also allocates space for a Wilma but specifies the
current value of *x.p_ (that is , the contents of the class Wilma
object that x.p_ points to) should be used to initialize the newly
created Wilma.
The net result is that x.p_ and y.p_ each point to a separate object
of type Wilma but both objects contain the same data. (In a perverse
design, the Wilma default and copy constructors could cause the
contents to differ.)
--
Remove del for email