I have a C++ framework being built in the latest version of Xcode (9.4.1 at the time of writing) that I am using from Objective-C++ code, again within Xcode. I need to perform a dynamic_cast
from one pointer type to another. However, the dynamic_cast
is only working from a Debug build and is not working from a Release build. Is there something I'm missing or understanding about how dynamic_cast
works here within Objective-C++ that makes this sample fail?
C++ Framework
TestClass.hpp
class Parent {
public:
// https://stackoverflow.com/a/8470002/3938401
// must have at least 1 virtual function for RTTI
virtual ~Parent();
Parent() {}
};
class Child : public Parent {
public:
// if you put the implementation for this func
// in the header, everything works.
static Child* createRawPtr();
};
TestClass.cpp
#include "TestClass.hpp"
Parent::~Parent() {}
Child* Child::createRawPtr() {
return new Child;
}
Objective-C++ Command Line App
main.mm
#import <Foundation/Foundation.h>
#import <TestCastCPP/TestClass.hpp>
int main(int argc, const char * argv[]) {
@autoreleasepool {
Parent *parentPtr = Child::createRawPtr();
Child *child = dynamic_cast<Child*>(parentPtr);
NSLog(@"Was the cast successful? %s", child != nullptr ? "True" : "False");
}
return 0;
}
In both Debug and Release, I expect this code to print "True". However, in reality, Release mode prints "False". As a smoke test, the dynamic_cast
at this SO post works just fine.
Interestingly, the same sort of code works from a C++ command line application, again within Xcode. I have tried disabling the optimizer in Release mode, but this did not seem to fix the problem.
I have a sample project up on GitHub here. Remember to compile it in Release to see the reason for my question. I've included the TestCast
scheme for Objective-C++, and the TestCastCPP
scheme for the straight C++.