Could you explain this copy member function to me?
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_)) { }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class Wilma { };
class Fred {
public:
Fred() : p_(new Wilma()) { }
Fred(const Fred& f) : p_(new Wilma(*f.p_)) { }
~Fred() { delete p_; }
Fred& operator= (const Fred& f)
{
// Bad code: Doesn't handle self-assignment!
delete p_; // Line #1
p_ = new Wilma(*f.p_); // Line #2
return *this;
}
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
Wilma(*f.p_)
or
new Wilma(*f.p_)
is class Wilma incomplete?
Please explain it to me if you can.
Thanks,
new Wilma(*f.p_)
This line creates a new Wilma instance. It calls the copy constructor of Wilma.
Wilma::Wilma(const Wilma &rhs)
As we know that the default constructor and copy constructor are automatically generated, so we can't say Wilma incomplete.
Topic archived. No new replies allowed.