Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual functions in Objective C

Tags:

objective-c

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
like image 934
spandana Avatar asked May 10 '11 14:05

spandana


People also ask

What is virtual function in C?

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.

What is the difference between virtual function and function overriding?

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.

Which concept of OOP is shown by virtual functions?

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.

Why do we need virtual functions in C++?

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.


1 Answers

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
like image 92
Vladimir Avatar answered Sep 25 '22 07:09

Vladimir