Store derived class objects in base class variables

前端 未结 5 1003
一生所求
一生所求 2020-11-22 16:18

I would like to store instances of several classes in a vector. Since all classes inherit from the same base class this should be possible.

Imagine this program:

5条回答
  •  再見小時候
    2020-11-22 16:53

    TL;DR: You should not inherit from a publicly copyable/movable class.


    It is actually possible to prevent object slicing, at compilation time: the base object should not be copyable in this context.

    Case 1: an abstract base

    If the base is abstract, then it cannot be instantiated and thus you cannot experience slicing.

    Case 2: a concrete base

    If the base is not abstract, then it can be copied (by default). You have two choices:

    • prevent copy altogether
    • allow copy only for children

    Note: in C++11, the move operations cause the same issue.

    // C++ 03, prevent copy
    class Base {
    public:
    
    private:
        Base(Base const&);
        void operator=(Base const&);
    };
    
    // C++ 03, allow copy only for children
    class Base {
    public:
    
    protected:
        Base(Base const& other) { ... }
        Base& operator=(Base const& other) { ...; return *this; }
    };
    
    // C++ 11, prevent copy & move
    class Base {
    public:
        Base(Base&&) = delete;
        Base(Base const&) = delete;
        Base& operator=(Base) = delete;
    };
    
    // C++ 11, allow copy & move only for children
    class Base {
    public:
    
    protected:
        Base(Base&&) = default;
        Base(Base const&) = default;
        Base& operator=(Base) = default;
    };
    

提交回复
热议问题