ci******@lycos.com wrote:
This is what I have
class base{public:virtual ~base();};
class derived1 : public base {};
class derived2 : public base {};
class A
{
public:
A(base *b_):b(b_) {
}
A(const A&a)
{
//What to do here *************
}
private:
base *b;
};
I'm not sure how to write the copy constructor to make sure it makes
the right copy of b.
How would the copy constructor know which derived type to copy?
You can use the following smart pointer:
http://axter.com/smartptr
The smart pointer in the above link has a default policy to clone
(deep-copy) your derived type.
Moreover, you don't need to create a clone function for your base
class, because this smart pointer can automatically determine the
derived type by using the type pass to the constructor.
You would have to change your constructor to the following:
class A
{
public:
A(smart_ptr<base> b_):b(b_) {
}
A(const A&a):b(a.b)
{
//Now you don't have to do anything here
}
private:
smart_ptr<base> b;
};
If your A class only has the b member, you don't even need a copy
constructor for your A class, because the smart pointer will clone
automatically.
The smart_ptr is also more efficient and more flexible than the
boost::shared_ptr, which doesn't clone.
---------------------------------------------------------------------------*-------------
David Maisonave
http://axter.com
Top ten member of C++ Expert Exchange:
http://www.experts-exchange.com/Cplusplus
---------------------------------------------------------------------------*-------------