C + + virtual functions & pure virtual Functions & Abstract classes & interfaces & virtual base classes (GO)

Source: Internet
Author: User
Tags multiple inheritance in c


1. polymorphic

In object-oriented languages, many different implementations of interfaces are polymorphic. Polymorphism refers to an instance (object) of a child class with a pointer to the parent class, and then invokes the member function of the actual subclass through a pointer to the parent class .

Polymorphism is a pointer to a parent class type that allows a pointer to a subclass type, which is implemented by a virtual function .

Polymorphism allows the parent class to have a "multiple form" pointer, which is a generic technique. (The so-called generic technique is the attempt to use immutable code to implement a mutable algorithm).

2. Virtual functions

2.1 Virtual function definition

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

Virtual function return value type virtual function name (formal parameter list)
{function Body}

A virtual function must be a non-static member function (and non-constructor) of a class whose access rights are public.

2.2 Function of virtual function

The function of virtual function is to implement dynamic Union, that is, to select the appropriate member function dynamically during the running phase of the program, after defining the virtual function, the virtual function can be redefined in the derived class of the base class (IBID.). A function defined in a derived class should have the same number of parameters and formal parameter types (overrides) as a virtual function to achieve a uniform interface , with different definition procedures. If a virtual function is not redefined in a derived class, it inherits the virtual function of its base class.

Virtual functions can let member function operations generalize, when a base class pointer points to an object of a different derived class, the base class virtual member function calls the base class pointer, and it calls the member function of the object it really points to, not the member function defined in the base class (as long as the derived class overrides the member function). If it is not a virtual function, the function defined in the base class is called whenever the base class pointer points to a derived class object.

2.3 Implementation of dynamic linking requires three conditions:

1) The behavior that needs to be dynamically linked must be defined as the virtual function of the public property of the class;
2) There is a subtype relationship between classes, which generally manifests as one class deriving from another class public ;
3) You must first use the base class pointer to point to the object of the subtype , and then call the virtual function directly or indirectly using the base class pointer.

2.4 Defining limits for virtual functions

1) Non-class member functions cannot be defined as virtual functions, and static member functions and constructors in the class's member functions cannot be defined as virtual functions, but destructors can be defined as virtual functions.

2) You only need to use the keyword "virtual" in the class body of the declaring function to declare the function as a virtual function, and you 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 that has the same name as the member function and returns a value, the number of arguments, and the same parameter type cannot appear in the class. In a derived class with this class as the base class, you cannot also have this non-virtual same name with the same number of arguments as the argument type function.


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

If defined as a virtual function, then it is dynamically bound, that is, can be overridden in a derived class, which is inconsistent with the definition of a static member function (only one copy in memory, access to a static member through a class name or object reference).

2) Why the constructor cannot be a virtual function:

Because if the constructor is a virtual function, it will be constructed during execution, and the execution period requires that the object is already established, the function of the constructor is to establish the appropriate object, so it is impossible to perform polymorphic (the purpose of the virtual function is to achieve polymorphism) in the absence of a well-built object. In an inheritance system, the order of construction is from the base class to the derived class, and its purpose is to ensure that the object can be successfully constructed. The constructor assumes the creation of the virtual function table, if it is a virtual function, how to ensure the success of VTBL construction?

3) Virtual destructor

In C + + development, the destructor of the class used to do the base class is generally a virtual function. when there are virtual functions in the base class, the destructor is also defined as a virtual destructor . If you do not define a virtual destructor, when you delete a pointer to a derived class object, the destructor for the base class is called, and the destructor for the derived class is not called, resulting in a memory leak.
The virtual destructor works by: The destructor of the bottommost derived class is called first, and then the destructor of each base class is called. This way, when a pointer to a derived class is deleted, the destructor of the derived class is called first, and there is no memory leak.
In general, if there is no virtual function in the class, you do not have to declare the virtual destructor. Declare a virtual destructor when and only if the class contains at least one virtual function.
Destructors are only written as virtual functions when a class is used as a base class.

2.6 Realization of virtual function--virtual function table

Virtual functions are implemented by a table of virtual functions, referred to as v-table. the virtual function table of a class is a contiguous memory that records the address of a jmp instruction in each memory unit. The compiler creates a virtual function table for each class that has a virtual function, which is shared by all objects of the class , and each virtual function member of the class occupies a row in the virtual function table.
In this table, the Address table is primarily a virtual function of a class . This table solves the problem of inheritance, overwriting, and guaranteeing the actual function of its real response. In an instance of a class with virtual functions, memory is assigned to pointers to the table, so when you manipulate a subclass with a pointer to the parent class, the virtual function table indicates the function that should actually be called.

3. Pure virtual function

In many cases, it is not possible to give a meaningful implementation of a virtual function in a base class, it is declared as pure virtual function, and its implementation is left to the derived class of the base class to do .

Declaration format for pure virtual functions: Virtual < function return type descriptor > < function name > (< parameter table >) = 0;

The purpose of pure virtual functions is to provide a consistent interface for derived classes .

4. Abstract class

Abstract classes are classes that contain pure virtual functions (at least one pure virtual function), which cannot create objects (abstract classes cannot be instantiated), but can declare pointers and references for the interface declaration of the underlying class and the polymorphism of the runtime.

In an abstract class, there can be either an abstract method or a concrete method or a non-abstract method. Abstract classes can be either all abstract or non-abstract methods. A subclass that inherits from an abstract class, and only the abstract methods that implement all of the parent classes can be non-abstract classes.

5. Interface

an interface is a concept. It is implemented in C + + with abstract classes and interface in C # and Java.

Interfaces are specifically inherited. The meaning of an interface's existence is also inherited. Is the same as the pure virtual function in the abstract class in C + +. cannot be instantiated.
The keyword defining the 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 keyword that inherits the interface is implements, which is equivalent to the extends of the inheriting class. It is important to note that when an interface is inherited, all functions in the interface must be completely overwritten.
When you want to inherit multiple classes, the development program does not allow, error. This will use the interface. Because the interface allows multiple inheritance , the class is not allowed (multiple inheritance in C + +). So we need to use the interface.

6. Virtual base class

When you inherit a base class from a derived class, the virtual base class is inherited by adding a dummy keyword, such as:
Class Derive:virtual Public Base

The virtual base class is relative to its derived class, which can itself be a generic class . It is called a virtual base class only if its derived class is virtual , and it is called a base class if there is no virtual inheritance. For example, the virtual Class B inherits from Class A, that class A is called the virtual base class B, if there is no virtual inheritance, then the Class B is just the base class of Class A.
Virtual inheritance is primarily used in cases where a class inherits multiple classes, avoiding the repetition of inheriting the same class two or more times.
For example, Class A derives from Class B and Class C, and Class D inherits both Class B and Class C, at which point Class D avoids inheriting class A two times in a virtual inheritance way.

7. Abstract class vs Interface

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

Abstract classes can have a construction method, the interface cannot have a construction method;

There can be ordinary member variables in the abstract class, there are no ordinary member variables in the interface;

All methods inside the interface must be abstract, and the abstract class can have the method of realization;

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

Abstract classes can contain static methods, and interfaces cannot contain static methods;

Both abstract classes and interfaces can contain static member variables, and the access types of static member variables in an abstract class can be arbitrary, but the variables defined in the interface can only be public static final types, and the public static final type is the default.

8. Virtual function vs pure virtual function

Virtual functions
Introduction Reason: In order to facilitate the use of polymorphic properties, we often need to define virtual functions in the base class.
Pure virtual function
Reason for introduction:
1) with "virtual function";
2) In many cases, the base class itself generates objects that are unreasonable. 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.
Pure virtual function is the base class only defines the function body, there is no implementation process.
Pure virtual function is equivalent to interface, cannot direct instance, need derived class to implement function definition;
Some people might be wondering, what's the use of defining these?
For example, if you want to describe the attributes of something to someone else, and you don't want to implement it, you can define it as pure virtual function. Say a little more thorough, such as building buildings, you are the boss, you give the construction company to describe the characteristics of your building, how many floors, the roof to have a garden or something, construction companies can follow your method to achieve, if you do not clear these, perhaps the construction company does not know you need the characteristics of the building. With the pure need function can be very good division of labor.

The difference between the two:

If the 1> class is declared as a virtual function, this function is implemented, even if it is an empty implementation, its function is to allow this function in its subclasses can be overloaded, so that the compiler can use late binding to achieve polymorphism;
Pure virtual function is only an interface, is a function of the declaration, it is to be left in the subclass to achieve.

2> virtual functions can not be overloaded within subclasses, but pure virtual must be implemented in subclasses, just like Java interfaces. Usually we add a lot of functions to virtual, is a good habit, although sacrificing some performance, but increased the object-oriented polymorphism, because you can hardly anticipate that the parent class inside the function is not to modify its implementation of the child class;

The class of the 3> virtual function is used for "implement inheritance", inheriting the interface and inheriting the implementation of the parent class. Of course, we can also complete their own implementation. The classes of pure virtual functions are used for "interface inheritance" and are mainly used in communication protocols. The focus is on the unity of the interface, which is accomplished by subclasses. In general, there is only pure virtual function in the interface class;

4> classes with pure virtual functions are called abstract classes, which cannot be used without directly generating objects, but only after being inherited and overriding their virtual functions.

C + + virtual functions & pure virtual Functions & Abstract classes & interfaces & virtual base classes (GO)

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.