What is the equivalent of a C++ pure-virtual funct

2019-03-19 18:54发布

问题:

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