[Fwd: Re: cast operation]

From: Onuchin Valeriy (onuchin@sirius.ihep.su)
Date: Fri Jul 23 1999 - 11:13:07 MEST


Dear ROOTers. 
The following just to complete the story.
Best regards.		Valery


attached mail follows:


> class A > { > private: > Object* theGoal; > public: > Object* GetTheGoal() const { return theGoal; } > ... > }; > > class B; // some other class > > class C: public A, public B // multiple inherited > { > ... > }; > > B* d = new C(); > > // there are 2 choices to get pointer to theGoal > > Object* goal1 = ((A*)d)->GetTheGoal(); // cast B to A > Object* goal2 = ((C*)d)->GetTheGoal(); // cast B to C > > > questions: > > 0. what cast from above is correct? Are you using a very old compiler? If not, you should stop using the old C style casts and use the new ones: const_cast static_cast dynamic_cast reinterpret_cast I have no C++ book here right now, but I think what you're trying to do is a cross-cast. You cannot use old C style casts for this! The pointer will not be correct, so you'll have to use dynamic_cast instead: Object* goal1 = dynamic_cast<A*>(d)->GetTheGoal(); // cast B to A Object* goal2 = dynamic_casr<C*>(d)->GetTheGoal(); // cast B to C Now, here's the neat thing with dynamic_cast: If the cast isn't legal, it'll return null. So, you could do it like this: A* p1 = dynamic_cast<A*>(d); C* p2 = dynamic_cast<C*>(d); Object* goal1; Object* goal2; if(p1) goal1 = p1->GetTheGoal(); if(p2) goal2 = p2->GetTheGoal(); Back to your question: I do not know which cast to use, but if you try the above, you'll see which one it is, because p1 or p2 will be null, and the correct cast is then the cast which doesn't return null. > 1. if there are rules to avoid segmentation violation errors? You probably got a segmentation fault because, as I said, old C style casts can't do cross-casting, that is, casting back and forth within a multiple inheritance hierarchy. > 2. what is difference between declarations > class C: public A, public B > and > class C: public B, public A I don't think there's any difference, but if you're using Qt and signals and slots, QObject must be the first class: class D: public QObject, public whatever > 3. if cast operation is platform/compiler dependent ? The new cast operators as mentioned above might not be supported by all compilers yet.



This archive was generated by hypermail 2b29 : Tue Jan 04 2000 - 00:43:36 MET