2

I have two Objective-C classes and one is derived from the other as

@interface DerivedClass : BaseClass
{
}

The code section below belongs to BaseClass:

- (id)init {
    if (self = [super init]) {
       [self configure]; 
    }   
    return self;
}

- (void) configure{} //this is an empty method

And the code section belongs to the DerivedClass:

-(void) configure{
    NSLog(@"derived configure called");
}

Now, when I say derivedInstance = [DerivedClass new]; and watch the call stack, I see that the configure method of my derived class gets called at the [self configure] line of the base's init method.

I'm an Objective-C noob and I'm confused about how a method of a derived class gets called from the method of a base class. "self" keyword is explained to be the same thing as "this" keyword of some languages but I think this explanation is not completely correct, right?

1 Answer 1

6

[self someMessage] will send the message "someMessage" to the current object, which is an instance of DerivedClass.

Message dispatch is done dynamically at run-time, so it will behave as whatever the object is at that time.

Sign up to request clarification or add additional context in comments.

1 Comment

To expand on this very slightly: if a class doesn't implement a message that is passed to it, it'll check the superclass. That's the basis of inheritance. In your case, 'self' is a DerivedClass and does implement 'configure', so that's what ends up executing. If you remove the implementation of 'configure' from your derived class, the one in the superclass will end up being called instead.

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.