C++ vector of base class objects

后端 未结 2 2088
北恋
北恋 2021-01-21 09:33

If I have a base class and a derived class, I can create a vector of base class pointers, if I want to group multiple base and/or derived classes together in a container.

<
2条回答
  •  Happy的楠姐
    2021-01-21 10:13

    Yes you can use vector & the compiler won't raise any error for this usage. However, the problem with vector is that it fails to achieve polymorphism. See below :-

    #include 
    #include 
    using namespace std;
    
    class base
    {
        int x, id;
        static int i;
        public:
        base()
        {
            id = ++i;
            cout << "Base constructed: " << id << "\n";
        }
        base (const base &b)
        {
            id = ++i;
            cout << "Base copy constructed: " << id << "\n";
        }
        virtual int& getx()
        {
            cout << "Base getx() called\n";
            return x;
        }
        virtual ~base()
        {
            cout << "Base destroyed: " << id << "\n";
        }
    };
    int base :: i = 0; 
    
    class derived : public base
    {
        int x, id;
        static int j;
        public:
        derived()
        {
            id = ++j;
            cout << "Derived constructed: " << id << "\n";
        }
        derived (const derived& d)
        {
            id = ++j;
            cout << "Derived copy constructed: " << id << "\n";
        }
        virtual int& getx()
        {
            cout << "Derived getx() called\n";
            return x;
        }
        virtual ~derived()
        {
            cout << "Derived destroyed: " << id << "\n";
        }
    };
    int derived :: j = 0;
    
    int main()
    {
        vector v;
        v.emplace_back(derived());
        v[0].getx() = 7;
        cout << "\n\n";
        for (int i=0; i

    You can clearly see that although the object is of derived neither the copy constructor of derived is called nor getx() of the same. So the purpose of using vector to achieve polymorphism is defeated. Hence you should never use vector & rather prefer vectors of smart pointers or raw pointers.

提交回复
热议问题