The use of virtual function and pure virtual function in C + + _c language

Source: Internet
Author: User
Tags inheritance

In this paper, the usage of virtual function and pure virtual function in C + + is deeply analyzed, which is very important for learning and mastering object-oriented programming. The specific contents are as follows:

First, the core idea of object-oriented programming (object-oriented programming) is data abstraction, inheritance and dynamic binding . With data abstraction, you can detach the interface of a class from the implementation, and use inheritance to make it easier to define new classes that are similar but not identical to other classes , and use dynamic bindings to partly ignore the differences between similar classes, and to use their objects in a uniform way .

The function of virtual function is to realize polymorphism (polymorphism), polymorphism is to separate interface from implementation, adopt common method, but adopt different strategy because of individual difference. Pure virtual function is a kind of special virtual function. A virtual function is associated with polymorphism, and polymorphism is associated to inheritance. So this article is in the inheritance level of the fuss. Without inheritance, there is nothing to talk about.

One, virtual function

1. Defined

In C + +, the base class must distinguish between its two member functions: one that the base class expects its derived classes to overwrite, and one that the base class expects the derived class to inherit directly without changing it. For the former, the base class is defined as a virtual function (virtual) by adding the virtual keyword before the function.

Class base{//base class public 
: 
  virtual int func (int n) const; 
 
Class Derive_class:public base{public 
: 
  int func (int n) const;//default also virtual function 
}; 

When we overwrite a function in a derived class, we can add the virtual keyword before the function. This is not necessary, however, because once a function is declared as a virtual function, it is a virtual function in all derived classes. A non-static function other than any constructor can be a virtual function. A derived class often (but not always) overrides a virtual function that it inherits, and if the derived class does not overwrite a virtual function in its base class, the virtual function behaves like any other ordinary member, and the derived class inherits directly from its version in the base class.

2. Dynamic binding

Dynamic binding will occur when we call a virtual function using a reference (or a pointer) to a base class (binding). Because we don't know exactly which version of the virtual function is invoked until the runtime, the version in the base class may also be the version in the derived class, based on the true type of the object to which the reference (or pointer) is bound. Unlike a non-virtual function at compile-time binding, a virtual function is a version of a function that is selected at run time, so dynamic binding is also called run-time binding (Run-time binding).

3. static types and dynamic types

A static type is a type that is generated when a variable is declared, and is always known at compile time; a dynamic type refers to the type of an object in memory that is represented by a variable or expression, and it is unknown until run time. The call is resolved at run time only if the virtual function is called through a pointer or reference to a base class, and only in this case can the dynamic type of the object be different from the static type. If an expression is neither a reference nor a pointer, its dynamic type is always consistent with the static type.

4. Final and override

If a function is defined in a derived class that has the same name as a virtual function in a base class but differs from a formal parameter list, the compiler considers this to be a newly defined function of the derived class. This error is difficult to find if our intention is to override the virtual function. The intent is clearer by adding the override keyword at the end of the virtual function in the derived class. If we mark a function with override, but the function does not overwrite the existing virtual function, the compiler will make an error.

Class base{//base class public 
: 
  virtual int func (int a, int b) const; 
 
Class Derive_class:public base{public 
: 
  int func (int a) const override;//error, no overwrite virtual function 
}; 

If we define a class, we do not want it to be inherited. Or if you want a function that is not overwritten, you can designate a class or function as final, and then any attempt to inherit the class or overwrite the function will raise an error.

Class Base Final {/* *  /};   Base class cannot be inherited 
class Derive_class:public Base {/* */};   Error 
 
void func (int) const final;  Do not allow subsequent other classes to overwrite func (int)

5. The mechanism of evading virtual function

In some cases, we want a call to a virtual function not to be dynamically bound, but rather to force it to execute a specific version of a virtual function. You can use scope operators to do this.

Forcibly call the version of the function defined in the base class regardless of the dynamic type of the basep 
int a = Basep->base::func (42); 

If a derived class virtual function needs to invoke its base class version, but does not use the scope operator, the call at run time will be resolved to a call to the derived class version itself, resulting in infinite recursion.

Two, pure virtual function

1. Defined

To facilitate the use of polymorphic features, we often need to define virtual functions in the base class. In many cases, you cannot give a meaningful implementation of a virtual function in a base class. In order for virtual functions to do nothing in the base class, the concept of "pure virtual functions" is introduced, so that functions need not be defined. We can describe a virtual function as a pure virtual function (pure virtual) by writing =0 in the position of the function body (before the semicolon of the declaration statement). Where =0 can only appear in a virtual function declaration statement within a class:

Class base{//abstract base class public 
: 
  virtual int func (int n) const =0; 
 

It is important to note that we can also provide definitions for pure virtual functions, but the function body must be defined outside the class.

2. Abstract base class

Classes that contain (or do not overwrite direct inheritance) pure virtual functions are called abstract base classes (abstract base class). The abstract base class is responsible for defining the interface, and subsequent classes can overwrite the interface. If a pure virtual function is not redefined in a derived class, but simply inherits the pure virtual function of the base class, the derived class is still an abstract base class. Because the abstract base class contains pure virtual functions (not defined), we cannot create an object of an abstract base class, but we can declare pointers or references to abstract base classes.

Base base;  Error, cannot instantiate abstract base class 

Summarize:

The

①. virtual function must be implemented without the compiler being able to make an error. The

②. Parent class and subclass all have their own version of the virtual function. Dynamically bound at run time by polymorphic mode. The

③. can forcibly invoke the specified version of the virtual function through the scope operator. The

④. pure virtual function is declared as follows: virtual void funtion () = 0; Pure virtual functions do not need to be defined. Classes that contain pure virtual functions are abstract base classes, and abstract base classes cannot create objects, but can declare pointers or references to abstract base classes. After the

⑤. derived class implements a pure virtual function, the pure virtual function becomes a virtual function in the derived class, and its subclasses can then overwrite the function.

⑥. destructors should usually be virtual functions, which ensures that the correct destructor version is invoked at the time of the destructor.

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.