dynamic_cast

Started by
2 comments, last by bilsa 20 years ago
Hey guys! shouldn't this dynamic cast work?

class ISystem {
public:
	virtual void SysTest() = 0;
};

class CSystem : public ISystem {
public:
	void SysTest() {
		MessageBox(NULL,"System WORKS", "System WORKS", MB_OK);
	}
};

class TestInterface {
public:
	virtual void SomeFunction() = 0;
};

class TestImplementation : public TestInterface, public CSystem {
public:
	void SomeFunction() {
		MessageBox(NULL,"TestInterface WORKS", "TestInterface WORKS", MB_OK);
	}
};

//then I want to do some dynamic casts:

ISystem* pSystem = new TestImplementation();
//For what I know this should work shouldnt it?

TestInterface* pTestInterface = dynamic_cast<TestInterface*>(pSystem);
//And if not that then at least this one?

CSystem* pSystem2 = new TestImplementation();
TestInterface* pTestInterface = dynamic_cast<TestInterface*>(pSystem2);

The compiler is giving me this warning: warning C4541: 'dynamic_cast' used on polymorphic type 'ISystem' with /GR-; unpredictable behavior may result And when I run the application I'm getting a "Runtime error"... Does anyone know what this means? I thought this was the purpose of dynamic_cast ? thank you! [edited by - bilsa on April 12, 2004 9:08:27 AM]
Advertisement
You need to enable Run Time Type Information. In VC6 its a checkbox in Project / Settings / C++ tab.
He, thats right... forgot that one. But still the application craches on the dynamic_cast

I mean, it shouldn't make a "Runtime error" right?!
It should return a NULL in case it failes.


This is how I'm calling it more exactly:

//the ISystem* tmpSys interface pointer is filled...if(tmpSys != NULL) {	//now test if the interface can be used?	tmpSys->SysTest();	MessageBox(NULL,"The ISystem pointer works fine!","test",MB_OK);		//try casting it to the desired interface	TestInterface* pTestInterface = dynamic_cast<TestInterface*>(tmpSys);	MessageBox(NULL,"The dynamic cast works fine!","1",MB_OK);		if(pTestInterface != NULL) {		pTestInterface->Message();	}}


And the the Runtime error comes just before the second MessageBox...

[edited by - bilsa on April 12, 2004 9:46:56 AM]
Ok, the problem was that since the tmpSys pointer pointed to an object created in a DLL, and the DLL project didnt have RTTI enabled... only the engine had it enabled, the application failed...

Works just fine now...

This topic is closed to new replies.

Advertisement