0

I have some problems with implementing class which written in C++, because I not familiar with c++ .. if someone could help with implementing it in Objective C

#ifndef ENTITY_H
#define ENTITY_H

class BaseGameEntity
{

private:

  int          m_ID;
  static int  m_iNextValidID;

  void SetID(int val);

public:

  BaseGameEntity(int id)
  {
    SetID(id);
  }

  virtual ~BaseGameEntity(){}

  virtual void  Update()=0;

  int           ID()const{return m_ID;}  
};



#endif


#include "BaseGameEntity.h"
#include <cassert>

int BaseGameEntity::m_iNextValidID = 0;

void BaseGameEntity::SetID(int val)
{
  assert ( (val >= m_iNextValidID) && "<BaseGameEntity::SetID>: invalid ID");

  m_ID = val;

  m_iNextValidID = m_ID + 1;
}
1
  • 1
    Are you receiving a specific error? Commented May 17, 2010 at 17:24

1 Answer 1

1

This is rougly equivalent to that C++ class:

// In BaseGameEntity.h
#import <Cocoa/Cocoa.h>

@interface BaseGameEntity : NSObject {
    NSInteger m_ID;
}

- (id)initWithID:(NSInteger)ID;
- (void)update; // must be defined by subclasses
- (NSInteger)ID;
@end


// In BaseGameEntity.m
#import "BaseGameEntity.m"

@implementation BaseGameEntity
static NSInteger m_iNextValidID;

- (id)initWithID:(NSInteger)ID {
    self = [super init];
    if (!self)
        return nil;
    NSAssert2(ID >= m_iNextValidID, @"%s invalid id: %d", __PRETTY_FUNCTION__, ID);
    m_ID = ID;
    m_iNextValidID = m_ID + 1;
    return self;
}

- (NSInteger)ID {
    return m_ID;
}

- (void)setID:(NSInteger)newID {
    NSAssert2(newID >= m_iNextValidID, @"%s invalid id: %d", __PRETTY_FUNCTION__, newID);
    m_ID = newID;
    m_iNextValidID = m_ID + 1;
}
@end

A few differences to note:

  • All methods are virtual in Objective-C, so there's no need to declare them as such
  • Objective-C doesn't have pure virtual functions
  • Objective-C doesn't have class-static variables — it only has function-static and file-static variables like C does — so we declare the static int in the implementation file
  • I included the setID: method for equivalence, but it's considered bad form to use setters in Objective-C initializers, so it's never actually called — I just copied the body of the method into the init method
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, especially for the comments :))
What will be better? For the update() leave it as it is or to adopt by the protocol? @protocol Instantiating - (void) update; @end
The normal way to force a subclass to provide its own implementation is to have the superclass declare it as part of its interface but raise an exception when the method is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.