1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#include <iostream>
#include <vector>
#include <typeinfo>
using namespace std;
class Clonable
{
public:
class Base
{
public:
virtual ~Base()
{}
virtual Base *clone() const = 0;
};
private:
Base *d_bp;
public:
Clonable()
:
d_bp(0)
{}
~Clonable()
{
delete d_bp;
}
Clonable(Clonable const &other)
{
copy(other);
}
Clonable &operator=(Clonable const &other)
{
if (this != &other)
{
delete d_bp;
copy(other);
}
return *this;
}
// New for virtual constructions:
Clonable(Base const &bp)
{
d_bp = bp.clone(); // allows initialization from
} // Base and derived objects
Base &get() const
{
return *d_bp;
}
private:
void copy(Clonable const &other)
{
if ((d_bp = other.d_bp))
d_bp = d_bp->clone();
}
};
class Derived1: public Clonable::Base
{
public:
Derived1()
{}
Derived1(Derived1 const &other)
{}
~Derived1()
{}
virtual Clonable::Base *clone() const
{
return new Derived1(*this);
}
};
int main()
{
vector<Clonable> bv;
{
Derived1 d1;
bv.push_back(d1);
}
cout << "==\n";
cout << typeid(bv[0].get()).name() << '\n';
cout << "==\n";
vector<Clonable> v2(bv);
cout << typeid(v2[0].get()).name() << '\n';
cout << "==\n";
}
|