0

I have a function that I want to declare and use in a typical C++ style within a class.

Hypothetical example definition from .mm file:

float MyClass::getRectArea(float width, float height){
  return width*height;
}

How can I declare this function in the objective-C class header/.h file?

@interface MyClass

//???

@end

3 Answers3

1

You could just write it as a function, just like you would in C++ — only it wouldn't be part of the class, because functions aren't part of classes in Objective-C. If you wanted it to be part of a class, you could make it a class method along the lines of:

+ (float)rectAreaWithWidth:(float)width height:(float)height {
    return width * height;
}

I would probably not make it an instance method, as suggested in another answer, because it really doesn't have anything to do with a particular object value — it's a pure function of its arguments.

Chuck
  • 234,037
  • 30
  • 302
  • 389
0

You can declare it as

-(float)getRectArea:(float)width getheight:(float)height; 

Then in the .m file, you can define it as

-(float)getRectArea:(float)width getheight:(float)height {
     return width*height;
 }

You can call it as follows

float area = [self getRectArea:5.0 getheight:4.0];

For more details and explanation see Method Syntax in Objective C

Community
  • 1
  • 1
Dinesh
  • 2,194
  • 3
  • 30
  • 52
0

If you want MyClass to be a C++ object then you would create the header as you normally would with C++.

MyClass.h

class MyClass
{
  public:
    float getRectArea(float width, float height);
};
bbarnhart
  • 6,620
  • 1
  • 40
  • 60