Q:

Alternative for this data structure(C++) in Objective-C

I have this data structure (struct) in C++:
struct Vector3f
{
    float x;
    float y;
    float z;

    Vector3f()
    {
    }

    Vector3f(float _x, float _y, float _z)
    {
        x = _x;
        y = _y;
        z = _z;
    }
};

I have been recently been learning and using Objective-C.  I have found that there are a lot of things that I can't do in Objective-C that I can in C++.  So, I want to be able to do this in Objective-C with the constructors.  I am aware that Objective-C doesn't support function overloading like C++.  So, the first constructor isn't required.

A:

You would simply use three properties:
@interface Vector : NSObject

@property(nonatomic, assign) float x, y, z;

- (id)init;
- (id)initWithX:(float)x y:(float)y z:(float)z;

@end

@implementation Vector

- (id)init {
    // Members default to 0 implicitly.
    return [super init];
}

- (id)initWithX:(float)x y:(float)y z:(float)z {
    if (self = [super init]) {
        self.x = x;
        self.y = y;
        self.z = z;
    }

    return self;
}

@end

Note that overriding init here is optional, since all it does is calling the superclass’ init method.

