about dynamic casting



#include<iostream>
using namespace std;

class base
{
public:

virtual void fun()
{
cout<<" base ::fun()"<<endl;
}

};

class derived :public base
{
public:

void fun()
{
cout<<" derived ::fun()"<<endl;
}

};

int main()
{
base *p,b;
derived d;
p=&b;
base *b1;
if(b1==dynamic_cast<base*>(p))
cout<<" base class pointer"<<endl;
else
cout<<"other"<<endl;

p=&d;

if(b1==dynamic_cast<derived*>(p))
cout<<"base";
else
cout<<" derived class pointer"<<endl;

return 0;
}

I have run above program and got following out.

other

derived class pointer

I can understand "derived class pointer" output but could not understand "other"
output. AS I was suspecting "base class pointer" output.

Could anyone point out on this result
You're not using the concept correctly.

You declare b1 to be of type base*, but you don't assign it a value; it's uninitialised. You then compare that value with some other pointer, p. That doesn't test anything.
ohh but it is base class pointer . so i had impression that it should work..

what would be the correct example of the dynamic_casting

not really. you are just comparing the addresses where the pointer points to.
which is why in both cases b1 is pointing to some uninitialized value and it never passes the equality test so you'll always get to the else clause.

more importantly though, why do you want to compare?
Nothing i was going through the dynamic_cast topic and want to understand how does it work
but i think i did mistake on pointer assignment itself
Topic archived. No new replies allowed.