What is the equivalent of a C++ pure-virtual function in Objective-C?

依然范特西╮ 提交于 2019-12-03 17:20:49

问题


Simple answer would be Protocol.

The another point is that it is said that all methods in ObjectC are virtual, so no need to say virtual in ObjC.

I find it hard to understand this concept.

Any comments to figure out more clear around this question ?

Thanks for commenting.


回答1:


Simple answer would be Protocol.

Simple but wrong. A protocol is an interface specification. It's a collection of messages that an object must (ignoring the @optional keyword for now) respond to.

The term "virtual function" has no direct counterpart in Objective-C. In Objective-C you don't call functions on objects, you send messages to them. The object itself then decides how to respond to the message, typically by looking up the message in its class object, finding the associated method and invoking it. Note that this all happens at run time, not compile time.

The mapping between messages (or "selectors" to give them their technical term) and methods is built entirely from the @implementation. The method declarations in the @interface are only there to give the compiler the information it needs to warn you that you may have forgotten a method implementation. And it is only a warning because you can't tell until run time whether whether the object really does respond to the message or not. For example, somebody else could add a category to an existing class that provides implementations for missing methods, or a class could override forwardingTargetForSelector: to forward messages it doesn't respond to elsewhere.




回答2:


Methods on objects in Objective-C are not virtual functions, they are real functions.

I beg to differ, methods in Obj-C aren't quite real like one would expect. They behave just like virtual functions in C++ do, except you cannot make a 'pure virtual' function in Objective-C.

Cheers, Raxit



来源:https://stackoverflow.com/questions/4374677/what-is-the-equivalent-of-a-c-pure-virtual-function-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!