File: virtcons2.cc

package info (click to toggle)
c%2B%2B-annotations 7.2.0-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 11,484 kB
  • ctags: 2,902
  • sloc: cpp: 15,844; makefile: 2,997; ansic: 165; perl: 90; sh: 29
file content (103 lines) | stat: -rw-r--r-- 2,254 bytes parent folder | download | duplicates (2)
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
94
95
96
97
98
99
100
101
102
103
    #include <iostream>
    #include <vector>
    #include <typeinfo>

    class Base
    {
        public:
            virtual ~Base();
            virtual Base *clone() const = 0;
    };

        inline Base::~Base()
        {}

    class Clonable
    {
        Base *d_bp;

        public:
            Clonable();
            ~Clonable();
            Clonable(Clonable const &other);
            Clonable &operator=(Clonable const &other);

            // New for virtual constructions:
            Clonable(Base const &bp);
            Base &get() const;

        private:
            void copy(Clonable const &other);
    };

        inline Clonable::Clonable()
        :
            d_bp(0)
        {}
        inline Clonable::~Clonable()
        {
            delete d_bp;
        }
        inline Clonable::Clonable(Clonable const &other)
        {
            copy(other);
        }

        Clonable &Clonable::operator=(Clonable const &other)
        {
            if (this != &other)
            {
                delete d_bp;
                copy(other);
            }
            return *this;
        }

        // New for virtual constructions:
        inline Clonable::Clonable(Base const &bp)
        {
            d_bp = bp.clone();      // allows initialization from
        }                           // Base and derived objects
        inline Base &Clonable::get() const
        {
            return *d_bp;
        }

        void Clonable::copy(Clonable const &other)
        {
            if ((d_bp = other.d_bp))
                d_bp = d_bp->clone();
        }

    class Derived1: public Base
    {
        public:
            ~Derived1();
            virtual Base *clone() const;
    };

        inline Derived::~Derived1()
        {
            std::cout << "~Derived1() called\n";
        }
        inline Base *Derived::clone() const
        {
            return new Derived1(*this);
        }

    using namespace std;

    int main()
    {
        vector<Clonable> bv;

        bv.push_back(Derived1());
        cout << "==\n";

        cout << typeid(bv[0].get()).name() << endl;
        cout << "==\n";

        vector<Clonable> v2(bv);
        cout << typeid(v2[0].get()).name() << endl;
        cout << "==\n";
    }