Home >Backend Development >C#.Net Tutorial >What is a virtual function

What is a virtual function

清浅
清浅Original
2019-05-05 16:54:4815973browse

Virtual function refers to: a member function declared as virtual in a base class and redefined in one or more derived classes, that is, a member function modified by the virtual keyword; the format is "virtual function" Return type function name (parameter list) {function body}".

What is a virtual function

A member function declared as virtual in a base class and redefined in one or more derived classes, the usage format is: virtual Function return type Function name (parameter list) {Function body}; To achieve polymorphism, access the overriding member function of the same name in the derived class through the base class pointer or reference pointing to the derived class.

Simply put, those member functions modified by the virtual keyword are virtual functions.

First of all: emphasize the concept that defining a function as a virtual function does not mean that the function is an unimplemented function. It is defined as a virtual function to allow the function of the subclass to be called using a pointer of the base class. Defining a function as a pure virtual function means that the function is not implemented. The purpose of defining a pure virtual function is to implement an interface and serve as a specification. Programmers who inherit this class must implement this function.

Example:

class A
{
public:
virtual void foo()
{
cout<<"A::foo() is called"<<endl;
}
};
class B:public A
{
public:
void foo()
{
cout<<"B::foo() is called"<<endl;
}
};
int main(void)
{
A *a = new B();
a->foo(); // 在这里,a虽然是指向A的指针,但是被调用的函数(foo)却是B的!
return 0;
}

This example is a typical application of virtual functions. Through this example, you may have some concepts about virtual functions. It is based on the so-called "deferred binding" or "dynamic binding". The call of a class function is not determined at compile time, but at run time. Since it is not possible to determine whether the function being called is a function of the base class or a derived class when writing the code, it is called a "virtual" function. Virtual functions can only achieve polymorphic effects with the help of pointers or references.

The above is the detailed content of What is a virtual function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn