jeudi 30 janvier 2020

How to use dynamic_cast on vector? [duplicate]

#include <bits/stdc++.h>
using namespace std;

struct Base{

    Base() {};
    virtual ~Base() {};
};

struct Derived: Base
{
  int k;  
};

int main() {

    vector<Base> outBase;

    Derived dtemp;
    dtemp.k =10 ;

    outBase.push_back(dtemp);

    Derived& dNow = dynamic_cast<Derived&>(outBase[0]);

    return 0;
}

The above code gives execution error.

Here, at first I am storing a derived class object into a Base class vector. Then from that vector I need to get the stored data into another derived object. The main importance is to learn how to get the data that was stored in vector of type Base into a derived class object using dynamic cast !

But if Derived& dNow = dynamic_cast<Derived&>(dtemp); is done then there is no error or exception . Please note the moto is how to read the data(in the form outBase[i]) from vector of type Base into a Derived class object using dynamic cast .

Aucun commentaire:

Enregistrer un commentaire