0

How I can instantiate a Objective-c class into CPP class?

for example my CPP class:

class Foo{
public:
    Foo();
private:
    MyObjcClass* myObjcClass; //it does not work
}

how I can do this?

note I using .m for Objective-C and .cpp for C++.

Thanks a lot!

justin
  • 104,054
  • 14
  • 179
  • 226
ademar111190
  • 14,215
  • 14
  • 85
  • 114

2 Answers2

3

Either

  • compile as Objective-C++
  • or declare it as id.

If you use id, you should introduce the type in your definitions, e.g.:

// Foo.mm
Foo::~Foo() {
  MyObjcClass * a = this->myObjcClass;
  [a release];
}

In general, you should preserve the type (MyObjcClass) and avoid using id, but declaring the variable as id is compatible with C and C++, so you can use id to avoid compiling everything that includes Foo.hpp as ObjC++.

justin
  • 104,054
  • 14
  • 179
  • 226
  • 1
    @ademar111190 perhaps you are looking for: `Foo::Foo() : myObjcClass([MyObjcClass new]) {}`? if you chose `id`, only `Foo` would need to change to compile as ObjC++, but everything that saw Foo would need just C++. – justin Nov 07 '12 at 19:23
  • 1
    perfect!!! dataDownload = [DataDownload new]; work too, but a very thank you justin :) – ademar111190 Nov 07 '12 at 19:30
1

There are two ways to do this. The sane way is to use Objective-C++. You can either do this with files that have a .mm extension or you can change your build settings. The default is to compile based on the file extension, but you can force it use Objective-C++ on a .cpp or .m file.

The crazy way is to use the raw Objective-C interface in objc.h.

IronMensan
  • 6,761
  • 1
  • 26
  • 35
  • Both true, but there's a third way, which is to just use `id` in all the pure C++ code, and move the code that must be ObjC (or ObjC++) into separate files, as justin suggests. – abarnert Nov 07 '12 at 20:12