How to declare the virtual functions in Objective C.
virtual void A(int s);
How to declare the same in Objective C.
-(void)A:(int)s //normal declaration
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
Conclusion. Function overriding in C++ is a runtime polymorphism, where we redefine a base class's method in the derived class. When working with reference or pointer objects, we should declare a function as virtual in the base class, if we intend to override it in the derived class.
Explanation: The functions which may give rise to ambiguity due to inheritance, can be declared virtual. So that whenever derived class object is referred using pointer or reference to the base class methods, we can still call the derived class methods using virtual function.
A virtual function in C++ helps ensure you call the correct function via a reference or pointer. The C++ programming language allows you only to use a single pointer to refer to all the derived class objects.
Objective-c does not support virtual functions, or to say that another way - all functions in obj-c classes are virtual as method calls are determined in run-time.
If your subclass overrides method from superclass and you reference subclass instance using pointer to superclass then subclass method will get called:
@interface A{
}
-(void) someMethod;
@end
@interface B : A{
}
-(void) someMethod;
@end
...
A* obj = [[B alloc] init];
[obj someMethod]; // method implementation from B will be called
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With