Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a pure virtual method in Objective-C

I want to go to there. Seriously though, how does one implement a pure virtual method in an "Apple" way? Do you use a Protocol with your base class and throw exceptions on those methods?

like image 827
Chris Avatar asked Mar 07 '11 16:03

Chris


3 Answers

When you program in Objective-C you need to purge your mind of such things as virtual methods. You don't call methods on Objective-C objects, you send messages to them. Objects either respond to messages or they don't, but due to the dynamic binding, you can't tell this until run time.

Thus, you can declare a method on a base object and not not provide an implementation, no problem (except for the compiler warning), but you can't have the compiler flag up when you directly instantiate an object with such methods and it won't throw an error at runtime unless you actually send that message to the object.

The best way to create "virtual" base classes (in my opinion) is to declare the method and give it a stub implementation that throws a suitable exception.

like image 150
JeremyP Avatar answered Oct 27 '22 23:10

JeremyP


In Objective-C, there is no pure virtual support as in C++.

A simulation would be that you declare a method in your interface but don't implement it in your .m file. Of course you'd get compiler warnings but IIRC you can turn those off. But you won't get warnings/errors if you don't overwrite them in the subclass, which you get in C++ (IIRC).

An alternative would be to implement them with just an NSAssert(NO, @"Subclasses need to overwrite this method"); body. Still, you'd only catch this at runtime, not compiletime.

like image 33
DarkDust Avatar answered Oct 27 '22 21:10

DarkDust


Depending on what you're doing the delegate pattern may be more appropriate than a subclass, where the delegate is defined as id<YourDelegateProtocol>. The compiler will generate a warning if the required methods in the delegate protocol are not implemented.

Subclassing is generally avoided in Objective-C since objects cannot inherit from multiple superclasses but they can implement multiple protocols.

like image 7
Matt Stevens Avatar answered Oct 27 '22 22:10

Matt Stevens