Dynamic_cast working right?

Started by
3 comments, last by HugosHoH 16 years, 4 months ago
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.
Advertisement
Your first cast is an illegal downcast, which causes undefined behavior. You can't make any assumptions about anything that happens after that.
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????
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.
ic thanks.

This topic is closed to new replies.

Advertisement