Dec 092008
 

Just figured this out and it caused me about 3 hours of pain, so I figured I’d post it in case I need to do it again.

You might find this necessary if you have some code like this:

This code will toss strange errors such as EXC_BAD_ACCESS and other kernel alarms. I’m not certain way this happens, but I think it is because Derived in the second example isn’t actually an instance of Base since the compiler doesn’t understand that Base is polymorphic. If you try to apply a dynamic_cast operator rather than the pointer cast (as used in example #2) the compiler will complain. What is probably happening is that at runtime the memory for the Derived is not correct because it was cast to a Base, and the kernel freaks out when you attempt to access something in Derived.

Another classic example of C++’s power causing major issues at runtime. These types of problems are not only tricky to figure out, but really only make sense to the kernel and compiler and aren’t obvious from a OO perspective.

Most modern OO languages would have absolutely no issues with the above code, and all dynamic OO languages wouldn’t even need the casts at all and would duck type the invocations via dynamic method invocation.

  One Response to “Writing a marker interface in C++”

  1. […] you can see, I was checking for NULL and yet I kept getting this error. Now, this guy confirmed that I was pointing to an invalid pointer. So I figured that somehow my GameObjectManager […]

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">