Store derived class objects in base class variables

前端 未结 5 1012
一生所求
一生所求 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:51

    // Below is the solution by using vector vect,
    // Base *pBase , and initialized pBase with
    // with the address of derived which is
    // of type Derived
    
    #include 
    #include 
    
    using namespace std;
    
    class Base
    {
    
    public:
    
    virtual void identify ()
    {
        cout << "BASE" << endl;
    }
    };
    
    class Derived: public Base
    {
    public:
    virtual void identify ()
    {
        cout << "DERIVED" << endl;
    }
    };
    
    int main ()
    
    {
    Base *pBase; // The pointer pBase of type " pointer to Base"
    Derived derived;
    // PBase is initialized with the address of derived which is
    // of type Derived
    
    pBase = & derived;
    // Store pointer to object of Base class in the vector:
    vector vect;
    // Add an element to vect using pBase which is initialized with the address 
    // of derived
    vect.push_back(pBase);
    vect[0]->identify();
    return 0;
    }
    

提交回复
热议问题