Butaca
Butaca

Reputation: 426

Forward declaration of a namespaced C++ class in in Objective C

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!

Upvotes: 2

Views: 2632

Answers (4)

justin
justin

Reputation: 104698

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.

Upvotes: 5

N_A
N_A

Reputation: 19897

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

Upvotes: 2

wquist
wquist

Reputation: 2607

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.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490018

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.

Upvotes: 0

Related Questions