1
#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 .

Rohan Bose
  • 11
  • 2
  • 2
    `#include ` is not a standard header and even in the toolchains that define it is not intended to be included directly. Including it directly does the opposite of what it is supposed to do, reduce compilation times, slowing build times by something close to an order of magnitude. [It has other very bad effects covered here](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h), and as you can see from that link, using it improperly is seen by many as just shy of a [capital crime](https://en.wikipedia.org/wiki/Capital_punishment). – user4581301 Jan 30 '20 at 18:34
  • Hi @Barry . You have marked my ques as related to object slicing. But i m not getting the answer from that ques as my ques is abt using vector in dynamic cast. Please read the last few lines. – Rohan Bose Jan 30 '20 at 19:02
  • 2
    it is closely related. Your dynamic cast makes no sense, because the `Derived` you put in the vector are sliced and you only have `Base` instances in the vector – 463035818_is_not_an_ai Jan 30 '20 at 19:28
  • I added another similar question, its not the best duplicate, but I hope it helps – 463035818_is_not_an_ai Jan 30 '20 at 19:32

0 Answers0