Sign in to follow this  

Dynamic_cast working right?

This topic is 3667 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi Well...I think it's weird when I run the following code I got the message printed "Succeeded!," which means the dynamic_cast allows casting where it should not because actually we are down casting the object.

class X {
public:
	int x;

	virtual void m() {}
};

class Y : public X {
public:
	int y;
};

class Z : public Y {
public:
	int z;
};

X x;
Y y;
Z z;

void main()
{
	X *px; Y *py; Z *pz;

	pz = static_cast<Z *>(&x);

	py = dynamic_cast<Y *>(pz);
	if (py)
	    printf("\nSucceeded!");
}

Help appreciated.

Share this post


Link to post
Share on other sites
Your first cast is an illegal downcast, which causes undefined behavior. You can't make any assumptions about anything that happens after that.

Share this post


Link to post
Share on other sites
Good but the polymorphic information stored per object base is accessed through pointers of classes in the same hierarchy similarly, right? I mean the vtab location for all objects of the same hierarchy is allocated at the same offset and accessed independently of the pointer type????

Share this post


Link to post
Share on other sites
Quote:
Original post by HugosHoH
Good but the polymorphic information stored per object base is accessed through pointers of classes in the same hierarchy similarly, right? I mean the vtab location for all objects of the same hierarchy is allocated at the same offset and accessed independently of the pointer type????

Sure, but because it's illegal for a derived pointer to point to an object whose dynamic type is the base class, there's no need for a vtable lookup. All Zs are Ys, so the cast can succeed without even looking at the vtable.

Share this post


Link to post
Share on other sites

This topic is 3667 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this