Virtual method-my understanding

Source: Internet
Author: User

1. What is a virtual method?

In C ++, the keyword virtual is used to indicate that a member function has polymorphism. The traditional polymorphism is actually implemented by virtual functions using virtual tables, that is, virtual functions should be generated for polymorphism.

On msdn, this explains virtual: Virtual keywords are used to modify methods, attributes, indexers, or event declarations, and enable them to be overwritten in a derived class. The Implementation of Virtual members can be changed by the override member in the derived class.

I understand that virtual objects (Virtual Methods) are used to modify Member objects (methods, attributes, indexers, or event declarations.

2. When can I use virtual methods?

Virtual methods are generated for Object-Oriented polymorphism. To put it simply, one of the methods for implementing polymorphism in C # is to use virtual functions. To be more complex, it is because the core idea of OOP is to useProgramA language describes objects in the objective world and abstracts a model with high cohesion, low coupling, and ease of maintenance and expansion.

When we want to implement the same object, we can write the common part of this object or the common and easy-to-change features into a class and define it as a virtual method, however, when the sub-objects under this object are implemented, You can inherit the parent object class by inheriting the virtual method of the parent class. If the sub-objects have their own implementations, you can override the virtual method (with overrid) or choose to reproduce the virtual method (with new. In this way, we do not need to consider changingCode.

Let's take a text example. The following is an example of a program:

For example, birds fly in this action, but different birds fly in different ways, some slide, some trembling wings, although they all fly, but the specific implementation is very different. In our abstract model, it is impossible to take all the flying actions into account. How can we leave a good extension for the future, how can we deal with the varied flight movements of specific birds? For example, now I want to implement a kind of "Crane", which also has the characteristics of birds (such as flying behavior). How can I simply inherit "Birds ", instead of modifying the existing Code of the abstract model of "Birds", how to easily expand the system?

Therefore, virtual functions are introduced in the object-oriented concept to solve such problems.

Using a virtual function is to extract features that are common but easy to change or are unclear in the parent class as override ). Virtual functions are also the key to implementing polymorphism in OOP.

3. Sample Code:

Example of the first C:

Using system;
Namespace Peter
{
Public class birds
{
Public String wing; // wings
Public String feather; // feather
Public Virtual bool fly ()
{
// Empty to implement the subclass
}
}
// Sparrow
Public class Sparrow: birds
{
Public override bool fly ()
{
// Implement the sparrow flying action
}
}
// Phoenix
Public class Phoenix: birds
{
Public override bool fly ()
{
// Implement Phoenix flying
}
}

// Shooting birds
Public class shootbird (birds B)
{
If (B. Fly ())
{
//
}
}
Public class call ()
{
Static void main ()
{

// Note that the input of a "bird" class is declared as a parameter, rather than a specific "bird ". The advantage is that no matter how many
// Species of birds, as long as they are inherited from birds, are not mistaken :) (polymorphism)


// Sparrow fight
Shootbird (New sparrow ());
// Dozen cranes
Shootbird (New Phoenix ());
// It is a process of fighting birds. As long as I implement the definition of a specific bird (derived from "Flying Birds"), I can
// You do not need to modify the shootbird function and the bird base class.
Shootbird (New other birds ());
}
}
}

In this way, we only need to define the fly () behavior in the abstract model "Birds", indicating that all subclasses derived from this "Birds" will have the fly () behavior, as for how fly () is implemented, it is enough to implement the specific subclass without affecting the abstract model of "Flying Birds.

 

Example 2 C:

From the perspective of C # program compilation, what is the difference between a virtual function and other common functions? Generally, functions are compiled into the execution file by pre-binding during compilation (see the article "Purple Shadow" for details). The relative address of the function remains unchanged during the program running. During compilation, a virtual function is bound later, and its relative address is uncertain. It dynamically judges the function to be called Based on the object instance in the runtime, the class defined during the declaration is called the Declaration class, and the class instantiated during execution is called the instance class.
(For example, bird = new sparrow ();
In this case, birds are declared, and Sparrow is an instance. )

The specific inspection process is as follows:
(1) When a function of an object is called, the system will directly check the declared class of this object, that is, the declared class, to see whether the called function is a virtual function;
(2) If it is not a virtual function, it will directly execute the function. If there is a virtual keyword, that is, a virtual function, it will not immediately execute the function at this time, but will go to check the instance class of the object.
(3) In this instance class, he will check whether the virtual function is re-implemented in the definition of this instance class (through the override keyword). If yes, then execute the re-implemented function in the instance class. If no, the system will keep searching for the parent class of the Instance class and repeat the check in the instance class, until you find the first parent class to overwrite the virtual function, and then execute the rewritten function in the parent class.
By knowing this, you can understand the running results of the following code:

Class
{
Protected virtual func () // note virtual, indicating this is a virtual function
{
Console. writeline ("func in ");
}
}

Class B: A // note that B is inherited from Class A, so Class A is the parent class, and Class B is the subclass.
{
Protected override func () // note override, indicating that the virtual function is re-implemented.
{
Console. writeline ("func in B ");
}
}

Class C: B // note that C is inherited from Class B, so B is the parent class, and C is the subclass.
{
}

Class D: A // note that D is inherited from Class A, so a is the parent class, and D is the subclass.
{
Protected New func () // note new, indicating to overwrite the Same Name class in the parent class, instead of re-Implementing
{
Console. writeline ("func in D ");
}
}

static void main ()
{< br> A; // defines an object of Class. this a is the Declaration class of a
a B; // defines an object of Class a B. this a is the Declaration class of B
A C; // defines an object of Class A C. this a is the Declaration class of C
a d; // defines the object of Class A of D. this a is the Declaration class of D

A = new A (); // instantiate object A. A is an instance class of.
B = new B (); // instantiate the B object. B is the B instance class.
C = new C (); // instantiate the C object. c is the c instance class.
D = new D (); // instantiate D object. D is the instance class of D.

A. func ();
// Execute. FUNC: 1. first check the declared Class A 2. check to be a virtual method 3. switch to check instance Class A, it is itself 4. execute Method 5 in instance Class. output result func in
B. func ();
// Execute B. FUNC: 1. first check the declared Class A 2. check to be a virtual method 3. switch to check instance Class B, which has heavy loads. 4. execute the method in instance Class B 5. output result func in B
C. func ();
// Execute C. FUNC: 1. first check the declared Class A 2. check to be a virtual method 3. switch to check instance Class C, no heavy load 4. go to check the parent class B of class C, which has 5 of the reload. execute the func method in parent class B. 5. output result func in B
D. func ();
// Execute D. FUNC: 1. first check the declared Class A 2. check to be a virtual method 3. switch to check instance Class D, without overloading (this should be noted, although D has implemented func (), but does not use the override keyword, so it will not be considered as a heavy load) 4. to check the parent class A of class D, it is itself 5. execute the func method in parent class A. 5. output result func in
D D1 = new D ()
D1.func (); // execute func () in Class D and output the result func in D.
}

4. Differences between virtual methods and interfaces

If you have to compare the two, you can find a link. This trace of association has to start with the type of polymorphism. There are two types of polymorphism: base class polymorphism and interface polymorphism ). The use of virtual functions implements the root class inheritance polymorphism. From the perspective of the design pattern, the base class inheritance system describes the is-a problem. For example, a bird is a base class (parent class), and a sparrow and a crane inherit the Child class. Sparrow and Crane "is-a" birds. In addition to the base class inheritance polymorphism, we also have an interface inheritance polymorphism. As the name suggests, this polymorphism produces an inheritance system through the Inheritance (more specifically "Implementation") interface. From the perspective of the design pattern, the interface inheritance system describes the is-like-a (or can-do) problem (see another article on the blog.ArticleView the differences between abstract classes and interfaces in the design mode). For example, for a door with the alarm function, we need to implement the "alarm door" class, "alarm door" and "is-a" door, instead of an alarm, it's just the "is-like-a" alarm. Therefore, the alarm function of the "alarm door" must implement the alarm interface to implement the alarm function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.