Chris Hill
Chris Hill

Reputation: 1924

Forward declare a C++ class in an objective-C++ file?

I have an Objective-C++ file, and I have two classes: one Objective-C, one C++:

@implementation ClassA

....
// Create a copy of MyClass and use it in another C++ class
instanceOfCppClassB->callFunction(new MyClass);

@end

class MyClass : public AnotherClass
{
....

};

This compiles and runs fine with the C++ class up on top, but I'd like to move it to the bottom. When I move it to the bottom I get the error:

Invalid use of incomplete type 'struct MyClass' Forward declaration of 'struct MyClass'

Regardless of using typedef,struct,@class I get no love. How do I forward declare this class?

Upvotes: 2

Views: 1573

Answers (2)

Dietrich Epp
Dietrich Epp

Reputation: 213258

Forward declaration of a C++ class does not allow you to use instances of the class, you can just pass them around. (To simplify the example, I have omitted any Objective-C.)

class Something;

void function(void)
{
    Something *x;         // Ok
    x = new Something();  // Error
    int z = x->field;     // Error
    x->method();          // Error
}

class Something : public Other { ... };

void function2(void)
{
    Something *x;         // Ok
    x = new Something();  // Ok
    int z = x->field;     // Ok
    x->method();          // Ok
}

You must put the entire definition of a class before you use it. The forward declaration only allows you to declare variables using the class's type.

So the answer is: what you ask is impossible. (What is wrong with putting the class definition at the top, anyway?)

You can still put methods at the bottom:

class Something {
public:
    void method();
};

@implementation ...
...
@end

void Something::method() { ... }

Upvotes: 2

nikola-miljkovic
nikola-miljkovic

Reputation: 670

Just add class MyClass Prototype before ClassA.

class MyClass;
....
@implementation ClassA
....

// Create a copy of MyClass and use it in another C++ class
instanceOfCppClassB->callFunction(new MyClass);

@end

Upvotes: 0

Related Questions