i was just reading this question here https://stackoverflow.com/a/332086/2689696 and it tells that dynamic cast
You can use it for more than just casting downwards -- you can cast sideways or even up another chain. The dynamic_cast will seek out the desired object and return it if possible.
so what does this really mean and what are the limitations/ conditions under which this can happen.
and i assume this is what the statement means. And the cast happens and i get a segmentation fault too which is obvious.
#include <iostream>
class base
{
public:
virtual void print () = 0;
};
class childa : public base
{
public:
char c1;
virtual void print ()
{
std::cout << "childa\n";
}
void printout()
{
std::cout << "childa out\n";
}
};
class childb : public base
{
public:
int c2;
virtual void print ()
{
std::cout << "childb\n";
}
void printin()
{
std::cout << "childb in\n";
}
void printout()
{
std::cout << "childb out\n";
}
};
int main()
{
base* b = new childa;
b ->print();
dynamic_cast<childa*>(b)->printout();
dynamic_cast<childb*>(b)->printout(); // cast happens here and the output is printed
dynamic_cast<childa*>(b)->c1 = 'a';
dynamic_cast<childb*>(b)->c2 = 2; // segfault here
}
This is the output i get and a segfault occurs
childa
childa out
childb outProcess returned -1073741819 (0xC0000005) execution time : 5.844 s
Press any key to continue.
EDIT: Yes it was foolish of me not to check for null value. but i wanted to know more about the comment from the other question(Up/Down/Sideways)