Virtual function/pure virtual function/abstract class/interface/virtual base class

Source: Internet
Author: User

1. Polymorphism

In the object-oriented language,Interface implementation methodsThat is, polymorphism. Polymorphism refers,Point the pointer of the parent class to the instance of the subclass.(Object), and thenCall the member functions of the actual subclass through the pointer of the parent class.

In Java, if no pointer exists, the Child class object is instantiated using the parent class.

Polymorphism allows a pointer of the subclass type to be assigned to a pointer of the parent class,Polymorphism is implemented through virtual functions,Polymorphism allows the pointer of the parent class to have multiple forms. This is a generic technology.

The so-called generic technology is trying to use the same code to implement variable algorithms.

2. Virtual Functions

In the class definition of the base class, define the general form of the virtual function:

Virtual function return value type virtual function name (parameter table)
{

Function body

}

A virtual function must be a non-static member function (and a non-constructor) of the class, and its access permission is public.

Functions of virtual functions

The role of a virtual function is to implementDynamic Association, That isDynamically select appropriate member functions during the running stage of the programAfter defining a virtual function, you can redefine the virtual function in the derived class of the base class (the same form as above ).

The function defined in the derived class should haveThe same number and type of parameters(Overwrite) To achieveUnified InterfaceDifferent Definition processes. If the virtual function is not redefined in the derived class, it inherits the virtual function of its base class.

Virtual functions can make member function operations generic. When the base class Pointer Points to objects of different Derived classes, the base class virtual member function calls the base class pointer, it calls the member function of the object to which it actually points,

Instead of the member functions defined in the base class (as long as the derived class overrides this member function ). If it is not a virtual function, the function defined in the base class will be called no matter which derived class object the base class pointer directs.

Three conditions are required for dynamic Association:

A. the behaviors that require dynamic association must be defined as ClassVirtual functions of public attributes;

B. There is a Subtype Relationship between classes, which is generally expressed as a class from another classPublic DerivationCome here;

C. You must first useBase Class pointer pointing to child type objectAnd then directly or indirectly use the base class pointer to call the virtual function.

Limits on defining virtual functions

1) Non-class member functions cannot be defined as virtual functions.Static member functionsAndThe constructor cannot be defined as a virtual function either.,You can define the Destructor as a virtual function..

2) You only need to use the keyword "virtual" in the class body of the declared function to declare the function as a virtual function, but do not need to use the keyword "virtual" when defining the function ".

3) If a member function is declared as a virtual function, a non-virtual function with the same name and return value, number of parameters, and parameter type cannot appear in this class.

In a derived class of the base class, such non-virtual functions with the same name and return values as the number of parameters and parameter type functions cannot appear.

Notes

1)Why cannot static member functions of a class be virtual functions:

If it is defined as a virtual function, it is dynamically bound, that is, it can be overwritten in the derived class, which is consistent with the definition of the static member function (there is only one copy in the memory, accessing static members through class names or object references.

2)Why cannot the constructor be a virtual function:

Because if the constructor is a virtual function, it will be constructed during the execution period, and the object needs to be created during the execution period. The work done by the constructor is to create an appropriate object,

Therefore, it is impossible to execute polymorphism (the purpose of a virtual function is to implement polymorphism) on an object that has not been constructed.

In the inheritance system, the construction sequence is from the base class to the derived class. The purpose is to ensure that the object can be successfully constructed. The constructor is responsible for creating the virtual function table. If it is a virtual function, how can we ensure the vtbl construction is successful?

3)Virtual destructor

During C ++ development, The Destructor used for base classes are generally virtual functions.When there are virtual functions in the base class, the Destructor should also be defined as a virtual destructor..

If you do not define a virtual destructor, When you delete a pointer to a derived class object, the base class destructor will be called. The destructor of the derived class is not called, causing memory leakage.

The method by which a virtual destructor works is: The destructor of the bottom-level derived class is called first, and the destructor of each base class is called. In this way, when you delete a pointer to a derived class,

The destructor of the derived class will be called first, so there will be no memory leakage.

Generally, if there are no virtual functions in the class, you do not need to declare the virtual destructor. Virtual destructor are declared only when the class contains at least one virtual function.

Only when a class is used as the base class can the Destructor be written as a virtual function.

Implementation of Virtual functions-virtual function table

Virtual functions are implemented through a virtual function table (V-table for short.The virtual function table of the class is a continuous memory.In each memory unit, record the address of a JMP command.

The compiler willCreate a virtual function table for each class with virtual functions. The virtual function table will be shared by all objects in the class.Each virtual function member of the class occupies a row in the virtual function table.

In this table, it is mainlyAddress Table of the class virtual function. This table solves the inheritance and overwrite issues and ensures that it reflects the actual functions.

The memory allocated to the pointer to this table is allocated to instances of classes with virtual functions. Therefore, when the pointer of the parent class is used to operate a subclass, this virtual function table specifies the actually called function.

3. Pure virtual functions

In many cases,If a base class does not provide meaningful implementation for a virtual function, it is declared as a pure virtual function. Its implementation is left to the derived class of the base class for implementation..

Declaration format of pure virtual functions:

Virtual <function return type specifier> <Function Name> (<parameter table>) = 0;

A pure virtual function is used to provide a consistent interface for the derived class..

4. abstract class)

An abstract class is a class that contains pure virtual functions (at least one pure virtual function). It cannot create objects (abstract classes cannot be instantiated), but can declare pointers and references, it is used for the declaration of basic class interfaces and the polymorphism of runtime.

Abstract classes can have either abstract methods or specific methods or non-abstract methods. Abstract classes can be both abstract methods and non-abstract methods.

A subclass inherited from an abstract class can be a non-abstract class only when all abstract methods of the parent class are implemented.

5. Interface

An interface is a concept. It is implemented using abstract classes in C ++.In C # and Java.

Interfaces are specially inherited. The meaning of an interface is also inherited. It is the same as the pure virtual function in the abstract class in C ++. It cannot be instantiated.

The keyword for defining an interface is interface, for example:

Public interface myinterface

{
Public void add (int x, int y );
Public void volume (int x, int y, int Z );
}

The key word of the inherited interface is implements, which is equivalent to extends of the inherited class. Note that,When an interface is inherited, all functions in the interface must be overwritten.

If you want to inherit multiple classes, the development program does not allow them and an error is returned. This requires an interface. Because the interface allowsMulti-InheritanceThe class does not allow (multiple inheritance is allowed in C ++ ). Therefore, interfaces are required.

6. virtual base class

When a derived class inherits the base class, a virtual keyword is added to the virtual base class inheritance, for example:

Class derive: virtual public Base
{
};

A virtual base class is relative to its derived class. It can be a common class..

Only its derived classVirtual inheritanceIt is called a virtual base class. If there is no virtual inheritance, it is called a base class.

For example, if Class B is inherited from Class A, Class A is called the virtual base class of class B. If there is no virtual inheritance, Class B is only the base class of Class.

Virtual inheritance is mainly used when a class inherits multiple classes, avoiding repeated inheritance of the same class twice or multiple times.

For example, Class A generates class B and class C, and Class D inherits both class B and class C. In this case, Class D must use virtual inheritance to avoid repeated inheritance of Class A twice.

7. abstract class vs Interface

A class can have multiple interfaces and can only inherit one parent class ??

Abstract classes can have constructor methods and interfaces cannot have constructor methods;

Abstract classes can contain common member variables, and interfaces do not contain common member variables;

All methods in the interface must be abstract, and the abstract class can have implemented methods;

The access type of abstract methods in the abstract class can be public or protected, but the abstract methods in the interface can only be public and the default type is public abstract;

Abstract classes can contain static methods. Interfaces cannot contain static methods;

The abstract class and interface can contain static member variables. The access type of static member variables in the abstract class can be any, but the variables defined in the interface can only be of the public static final type, the default value is public static final.

8. virtual functions vs pure virtual functions

Virtual Functions

Reason for introduction: to facilitate the use of polymorphism, we often need to define virtual functions in the base class.

Pure virtual functions

Reason for introduction:

1) Same as "virtual function ";

2) In many cases, it is unreasonable for the base class to generate objects. For example, an animal can be derived from sub-classes such as tigers and peacocks as a base class, but the object generated by the animal itself is obviously unreasonable.

A pure virtual function is a base class that only defines the function body and has no implementation process.

A pure virtual function is equivalent to an interface and cannot be directly used as an instance. A derived class is required to implement function definition;

Some people may wonder how to define these features?

For example, if you want to describe the attributes of some things to others and do not want to implement them, you can define them as pure virtual functions.

Let's talk about it more thoroughly. For example, if you build a building, you are the boss. You should describe to the construction company the characteristics of your building, the number of floors, and the roof should have a garden or something, construction companies can follow your methods to achieve it,

If you do not know this clearly, maybe the construction company doesn't know much about the characteristics of the building you need. The division of labor and cooperation can be well achieved with purely needed functions.

Differences between the two:

1) if it is declared as a virtual function in the class, this function is implemented. Even if it is an empty implementation, it is used to make this function reload in its subclass,

In this way, the compiler can use later binding to achieve polymorphism. A pure virtual function is just an interface and a function declaration. It should be left in the subclass for implementation.

2) virtual functions can also be not overloaded in the subclass. However, pure virtual functions must be implemented in the subclass, just like Java interfaces.

It is a good habit to add virtual functions to many functions. Although some performance is sacrificed, the object-oriented polymorphism is increased, it is hard to predict that the function in the parent class does not modify its implementation in the subclass;

3) the class of the virtual function is used for "implementation inheritance". The inherited interface also inherits the implementation of the parent class. Of course, we can also complete our own implementation.

Classes of pure virtual functions are used for interface inheritance and are mainly used for communication protocols. Focus on the uniformity of interfaces, and the implementation is completed by sub-classes. Generally, only pure virtual functions are involved in the interface class;

4) classes with pure virtual functions are called abstract classes. Such base classes cannot directly generate objects. They can only be used after they are inherited and overwritten.

Reference

1) http://www.cnblogs.com/fly1988happy/archive/2012/09/25/2701237.html

2) http://blog.csdn.net/trojanpizza/article/details/6556604

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.