What is the function of virtual function in C + +? How is it supposed to work?

Source: Internet
Author: User

A virtual function is associated with polymorphism, and polymorphism is associated with inheritance. So this article is on the inheritance level of the fuss. Without inheritance, nothing is to be talked about.

The following is an understanding of the virtual function of C + +.

One, what is a virtual function (if you do not know what the virtual function is, but have an urgent need to know, then you should start from here)

Simply put, those member functions that are modified by the virtual keyword are virtual functions. The function of virtual function, the use of professional terminology to explain is to achieve polymorphism (polymorphism), polymorphism is the interface and implementation of the separation, with the image of the language is to achieve a common approach, but because of individual differences and adopt different strategies. Let's take a look at some simple code

Class a{

Public

void print () {cout<< "This is A" &LT;&LT;ENDL;}

};

Class B:public a{

Public

void print () {cout<< "This is B" &LT;&LT;ENDL;}

};

int main () {//To make it easier to differentiate later, my main () code is called Main1

A;

b b;

A.print ();

B.print ();

}

With the print () interface of Class A and class B, we can see that these two classes adopt different strategies depending on the individual differences, and the output is what we expect, respectively, that is a and this is B. But is this really polymorphism? No, polymorphism There is also a key point is everything with a pointer to the base class or reference to manipulate the object. Now change the code at main ().

int main () {//main2

A;

b b;

A * p1=&a;

A * p2=&b;

P1->print ();

P2->print ();

}

Run a look at the results, Yo Ah, suddenly looking back, the result is two A. The problem is, P2 clearly points to the object of Class B but is called the print () function of Class A, which is not the result we expect, then we need to solve this problem to use the virtual function

Class a{

Public

virtual void print () {cout<< "This is A" &LT;&LT;ENDL;} Now it's a virtual function.

};

Class B:public a{

Public

void print () {cout<< "This is B" &LT;&LT;ENDL;} Do you need to add the keyword virtual to the front?

};

Undoubtedly, the member function print () of Class A has become a virtual function, so is the print () of class B a virtual function? The answer is yes, we simply set the member function of the base class to virtual, and the corresponding function of its derived class automatically becomes a virtual function. Therefore, the print () of Class B also becomes a virtual function. If you need to modify the virtual keyword before the corresponding function of the derived class, it is your own problem.

Now rerun the MAIN2 code so that the result of the output will be this is a and this is B.

Now to digest, I make a simple summary, the pointer to the base class when manipulating its Polymorphic class object, according to the different class object, the corresponding function is called, this function is a virtual function.



First: Emphasize a concept
Defines a function as a virtual function and does not represent a function that is not implemented.

Defines him as a virtual function to allow a pointer to a base class to invoke this function of a subclass.

Defines a function as pure virtual function, which means that the function is not implemented.

A pure virtual function is defined to implement an interface that acts as a specification, and a programmer who inherits this class must implement this function.

1. Introduction
Suppose we have the following class hierarchy:
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, which, by this example, may have some notion of virtual functions. It is virtual in the so-called "deferred" or "dynamic", the invocation of a class function is not determined at compile time, but is determined at run time. It is a "virtual" function because it is not possible to determine the function of the base class or the derived class when the code is written.
A virtual function can only be used with pointers or references to achieve polymorphic effects.
C + + pure virtual function
First, the definition
A pure virtual function is a virtual function declared in a base class that is not defined in the base class, but requires that any derived class define its own implementation method. The method of implementing a pure virtual function in a base class is to add "= 0" after the function prototype
virtual void Funtion1 () =0
Second, the reasons for the introduction
1, in order to facilitate the use of polymorphic features, we often need to define virtual functions in the base class.
2, in many cases, the base class itself is unreasonable to generate objects. For example, animals as a base class can be derived from tigers, peacocks and other sub-categories, but the animals themselves generated objects are obviously unreasonable.
In order to solve the above problems, the concept of pure virtual function is introduced, the function is defined as pure virtual function (method: Virtual ReturnType functions () = 0;), the compiler requirements must be overridden in the derived class to achieve polymorphism. A class that contains a purely virtual function is called an abstract class, and it cannot produce an object. This is a good solution to both of these problems.
A class that declares a pure virtual function is an abstract class. Therefore, the user cannot create an instance of the class, only instances of its derived classes can be created.
The most notable feature of pure virtual functions is that they must re-declare the function in the inheriting class (not the next = 0, otherwise the derived class cannot instantiate), and they are often not defined in the abstract class.
The purpose of defining a pure virtual function is to make a derived class simply an interface to an inherited function.
The meaning of pure virtual functions, so that all class objects (primarily derived class objects) can perform actions of pure virtual functions, but the class cannot provide a reasonable default implementation for pure virtual functions. So the declaration of a class pure virtual function is to tell the designer of the subclass, "You must provide a pure virtual function implementation, but I do not know how you will implement it."

Introduction to Abstract Classes
An abstract class is a special class that is built for abstraction and design purposes, and it is at the upper level of the inheritance hierarchy.
(1) The definition of abstract class: the class with pure virtual function is called abstract class.
(2) The role of abstract classes:
The primary function of an abstract class is to organize the operation as a result interface in an inheritance hierarchy, which provides a common root for derived classes, and the derived class implements the operation as an interface in its base class. So the derived class actually depicts the general semantics of the operation interface of a set of subclasses, which are also passed to subclasses, subclasses can implement these semantics concretely, and can pass these semantics to their own subclasses.
(3) Note When using abstract classes:
• Abstract classes can only be used as base classes, and implementations of their pure virtual functions are given by derived classes. If a pure virtual function is not redefined in a derived class, but only a pure virtual function of the base class is inherited, the derived class is still an abstract class. If the implementation of a base class pure virtual function is given in a derived class, then the derived class is no longer an abstract class, it is a concrete class that can be used to create objects.
• Abstract classes are objects that cannot be defined.

Summarize:
1, the pure virtual function declaration is as follows: virtual void funtion1 () = 0; Pure virtual functions must not be defined, and pure virtual functions are used to standardize the behavior of derived classes, that is, interfaces. A class that contains a pure virtual function is an abstract class, and an abstract class cannot define an instance, but it can declare a pointer or reference to a concrete class that implements the abstract class.
2, the virtual function declaration is as follows: Virtual returntype functionname (Parameter); Virtual function must be implemented, if not implemented, the compiler will error, errors are:
Error lnk****: unresolved external symbol "Public:virtual void __thiscall classname::virtualfunctionname (void)"
3. For virtual functions, both the parent and child classes have their own versions. Dynamically bound when called by polymorphic mode.
4, the realization of the pure virtual function of the subclass, the pure virtual function in the sub-class programming virtual function, sub-class subclass that the grandson class can override the virtual function, called by the polymorphic mode of the dynamic binding.
5. Virtual function is a mechanism used in C + + to realize polymorphism (polymorphism). The core idea is to access the functions defined by the derived class through the base class.
6, in the dynamic allocation of memory on the heap, the destructor must be virtual function, but there is no need to be pure virtual.
7, Friend is not a member function, only the member function can be virtual, so the friend cannot be a virtual function. However, you can solve the virtual problem of friends by having the friend function call the virtual member function.
8. The destructor should be a virtual function, and the destructor of the corresponding object type will be called, so if the pointer is to a subclass object, the destructor of the subclass is called and the destructor of the base class is automatically called.

Classes that have pure virtual functions are abstract classes that cannot generate objects and can only be derived. The pure virtual function of his derived class is not rewritten, and its derived class is an abstract class.
A pure virtual function is defined to make a base class non-instantiated
Because instantiating such an abstract data structure itself is meaningless.
or given the realization, it doesn't make sense.
In fact, I personally think that the introduction of pure virtual function is for two purposes
1, for the sake of security, because to avoid any need to clear but because of carelessness caused by the unknown results, remind the subclass to do the implementation should be done.
2, for efficiency, not the efficiency of program execution, but for the efficiency of coding.

What is the function of virtual function in C + +? How is it supposed to work?

Related Article

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.