2

Is it possible to do forward declaration of a C++ class, which is inside a namespace, in an Objective C header file?

C++ class to forward declare in Objective C:

namespace name
{
    class Clazz
    {

    };
}

I know I can if the C++ class is not in a namespace. Taken from http://www.zedkep.com/blog/index.php?/archives/247-Forward-declaring-C++-classes-in-Objective-C.html

Any thoughts?
Thanks guys!

1
  • What use is a forward declared C++ class? just use a #typedef void Clazz in that situation. Commented Apr 11, 2012 at 1:54

4 Answers 4

5

You just declare it as usual, and wrap it in the C++ #ifdef check when the header is also included in C and/or ObjC translations:

#ifdef __cplusplus
namespace name {
class Clazz;
} // << name
#endif

For obvious reasons, you cannot use name::Clazz in a C or ObjC translation, so this works out perfectly. You either need the forward declaration in the C++ translation, or it does not need to be visible to C or ObjC.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know about the __cplusplus definition. It is all clear now. Thanks.
2

You can forward declare your class as a struct in your objective-c++ headers and then include them in C or obj-c code. The same restrictions that normally apply also apply to this case. The only caveat is that you have to put ifdefs around the namespace so they don't show up when including your header in C code since the C compiler doesn't know about namespaces.

#ifdef __cplusplus
namespace name{
#endif
    struct classname;
#ifdef __cplusplus
}
using namespace name;
#endif

1 Comment

Your answer was useful too. Thanks!
1

You can declare a forward class in a namespace like this:

namespace MyNamespace
{
    class MyClass;
};

It should work in Obj-C++, but if not you could also try obj-c's @class, or just do a typedef void* Clazz.

1 Comment

Your answer was useful too. Thanks!
0

At least in normal C++, you'd do something like:

namespace a {
    class b;
}

int main(){
    a::b *c;
}

I can't say whether the Objective C compiler will accept that or not though.

1 Comment

objective-c is a pure superset of C so it wouldn't recognize the namespace identifier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.