C + + pure virtual functions, virtual functions, real functions, abstract classes, overloading, overriding, redefining

Source: Internet
Author: User

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

The function of virtual function is to realize polymorphism (polymorphism), which separates interface from implementation, adopts common method, but adopts 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 with inheritance.

One, virtual function

1. Defined

the virtual function of C + + is the main function of " run-time polymorphism ", the implementation of the virtual function is provided in the parent class, provide a default function implementation for subclasses .

  subclasses can override the virtual functions of the parent class to implement the specialization of subclasses .

The following is a virtual function in a parent class:

class a{public:    virtualvoid out2 (string  s)    {        cout<<"A (out2):"<<s<<Endl;    };

When we override 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 a derived class does not overwrite a virtual function in its base class, the virtual function behaves like other ordinary members, and the derived class directly inherits its version in the base class.

2. Dynamic binding

Dynamic binding occurs when we call a virtual function using the reference (or pointer) of the base class. Because we do not know which version of the virtual function is called until run time, it is possible that the version in the base class or the version in the derived class is judged by the true type of the object to which the reference (or pointer) is bound. Unlike non-virtual functions that are bound at compile time, virtual functions Select the version of the function at run time, so dynamic binding is also called runtime binding (Run-time binding).

3. static types and dynamic types

A static type refers to the type of the variable declaration or the type generated by the expression, which is always known at compile time; a dynamic type refers to the type of an object in memory represented by a variable or expression, which is unknown until run time. The call is resolved at run time only when the virtual function is called by a pointer or reference to a base class, and only in this case can the object's dynamic type 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.

Second, pure virtual function

1. Defined

A class containing pure virtual functions in C + + is referred to as an "abstract class." Abstract classes cannot use the new out object, only subclasses that implement the pure virtual function can be new out of the object .

Pure virtual Functions in C + + are more like "provide only declaration, no implementation", are the constraints of a subclass, and are " interface inheritance ".

Pure virtual Functions in C + + are also a "run-time polymorphism".

If the following class contains pure virtual functions, it is "abstract class":

class a{public:    virtualvoid out1 (string s) =0;     virtualvoid out2 (string  s)    {        cout<< A (out2): "<<s<<Endl;    }};

  Note that pure virtual functions should only be declared, without a specific definition, even if the definition of a pure virtual function is ignored by the compiler.

2. Reasons for 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 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.
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 overloaded in derived classes 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.

Three, common function (no-virtual)

  Normal functions are statically compiled, with no run-time polymorphism, and only call their own normal functions based on pointers or referenced "literal" class objects .

The normal function is the " enforced implementation " provided by the parent class for the child class.

Therefore, in an inheritance relationship, subclasses should not override the normal functions of the parent class, because the invocation of the function is related to the literal value of the class object.

Iv. overloading, overriding, redefining

   Heavy Duty Overload: Yesfunction names are the same, parameter lists are different. overloading exists only within the class. But it cannot be judged by the return type.overriding Override: Also called overlay. subclasses redefine virtual functions with the same name and parameters in the parent class . function features are the same.  But the concrete implementation is different, mainly in the inheritance relationship appears. Rewrite needs note: 1The overridden function cannot be static. It has to be virtual.2the overriding function must have the same type, name, and argument list3the access modifier for an overriding function can be different. For example: Although virtual is private, it is also possible to rewrite the overridden public,protected in a derived class.

  Redefine (redefining) is also called hiding:

Subclasses redefine non-virtual functions with the same name in the parent class (the argument list can be different).

if a class exists with the same function as the parent class, then this class will overwrite the method of its parent class, unless you cast it to the parent class type at the time of invocation, otherwise attempting to make a similar overload call to the child class and parent class is unsuccessful.

Five, virtual destructor function

Virtual destructor: Precede the destructor with the keyword virtual to illustrate that the destructor is a virtual destructor. Although a constructor cannot be declared as a virtual function, a destructor can be declared as a virtual function.

In general, if virtual functions are defined in a class, destructors should also be defined as virtual destructors.

VI. Abstract base class

Classes that contain (or inherit directly from) pure virtual functions are called abstract base classes (abstracted 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 only a pure virtual function of the base class is inherited, the derived class is still an abstract base class. Because the abstract base class contains pure virtual functions (not defined), we cannot create an abstract base class object, but can declare pointers or references to the abstract base class.

The reason why an abstract class exists is that it has an element of uncertainty. We do exist in those classes, but the member functions in the parent class that are not able to determine the specific implementation are called pure virtual functions. Pure virtual function is a special virtual function, it only declares, there is no specific definition.at least one pure virtual function exists in an abstract class, and a class with a pure virtual function must be an abstract class. Existence of pure virtual function is a necessary and sufficient condition for becoming abstract class.
  
#include <iostream>using namespacestd;classa{ Public:    Virtual voidOUT1 () =0;///Subclass Implementation    Virtual~A () {}; Virtual voidOut2 ()///Default Implementation{cout<<"A (OUT2)"<<Endl; }    voidOUT3 ()///Force Implementation{cout<<"A (OUT3)"<<Endl; }};classB: Publica{ Public:    Virtual~B () {}; voidout1 () {cout<<"B (OUT1)"<<Endl; }    voidOut2 () {cout<<"B (OUT2)"<<Endl; }    voidout3 () {cout<<"B (OUT3)"<<Endl; }};intMain () {A(A =NewB; AB-out1 (); AB-Out2 (); AB-out3 (); cout<<"************************"<<Endl; B*bb=NewB; BB-out1 (); BB-Out2 (); BB-out3 (); BB->A::OUT3 ();
DeleteAB; DeleteBB; return 0;}

Out3 () is a redefinition of a real function. Call ab->out3 () ;
Out2 () is a virtual function. Call Ab->out2 (); the object saved in BB is called
OUT1 () is just like Out2 (), except that the write function implementation is not required in the base class.
You can also implement virtual functions that call the parent class in a subclass by using the scope operator.

Summarize:

①. Virtual functions must be implemented without implementing a compiler error.

②. Both the parent and child classes have their own version of the virtual function. Dynamically bound at run time by polymorphic mode.

③. The specified virtual function version can be forcibly invoked by a scope operator .

④. Pure virtual function declaration is 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 you can declare pointers or references to abstract base classes.

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

⑥. Destructors should usually be virtual functions, which ensures that the correct destructor version is called at destructor time .

C + + pure virtual functions, virtual functions, real functions, abstract classes, overloading, overriding, redefining

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.