Many object-oriented state, class inheritance, virtual functions are summarized knowledge

Polymorphism

Polymorphic two, run-time and compile-time, also known as static binding, and dynamic binding. In general, we focus on dynamic binding, which is the run-time polymorphism, the polymorphism is implemented by the class inheritance and virtual functions are. The following said polymorphism is dynamic binding.

 

What is Polymorphism: polymorphism allows you to become a parent set equal to or more sub-objects of his technique, after the assignment, the parent object can be assigned to the characteristics of the child object based on the current in different mode of operation, sent the same message is possible when receiving different types of objects leads to a completely different behavior.

 

Polymorphic form must have three conditions :

1, there must be inheritance;

2, inheritance virtual function must have the same name ( which is the use of virtual functions Virtual function keyword declared in the base class, redefine the base class virtual function defined in a derived class, tells the compiler not statically linked to the function );

3, there is a base type pointer or reference, pointer or reference by the virtual function call;

 

In C ++, there is a method to achieve polymorphism: virtual function, an abstract class, cover, template

These concepts after slowly talk.

 

The following give an example of a virtual function, example, the base class is derived Shape into two classes:

#include <iostream>
using namespace std;

class Shape{
    protected:
        int width;
        int height;
    public:
        Shape(int a=0, int b=0){
            width = a;
            height = b;
        }
        
        virtual int area(){
            cout << "Parent class area:";
            return 0;
        }
}; 

Class the Rectangle : public the Shape {// inherited from the parent class when the Shape, it inherits all the properties and methods members
     public : 
        the Rectangle ( int A = 0 , int B = 0 ): the Shape (A, B) {} / / constructor inherited, wherein reusable code to multiplexing; of course, can be rewritten 
        
        int Area () { 
            COUT << " the Rectangle Area class: " ;
             return (width * height); 
        } 
}; 

class Triangle : public the Shape {
     public : 
        Triangle ( int A = 0 ,int B = 0 ): the Shape (A, B) {} 
        
        int Area () { 
            COUT << " Triangle class Area: " ;
             return (width * height / 2 ); 
        } 
}; 

int main () {
     the Shape * Shape; // must be a pointer to the base class, or will be error, a constant can not be assigned to 
    the rectangle REC ( . 4 , . 5 ); 
    Triangle Tri ( . 4 , . 5 ); 
    
    Shape = & REC; // Shape sub-object pointer to a rectangular 
    cout < <shape-> Area () << endl;
    
    Shape = & Tri; 
    COUT << shape-> Area () << endl; // Shape sub-object pointer points to a triangle 
    
    getchar (); 
    return  0 ; 
}

Note marked out the part, do not forget these points, which is an essential element constitute polymorphism.

 

NOTE: Once a function is illustrated as virtual function, regardless that it is inherited class number of layers, each layer in the derived class virtual function will always remain characteristics. That may have been inherited.

Note: virtual function can be redefined in a derived class or more, when redefined in a derived class, which function prototype (including the return type, function name, parameters) to be the base class is identical prototypes .

 

 

Virtual functions using the keyword in the base class virtual function declarations. When redefine the base class virtual function defined in a derived class, it tells the compiler not statically linked to the function .

What we want is any point in the program can be selected according to the type of object function calls invoked, this operation is called dynamic linking , or late binding .

Virtual function is the basis of dynamic binding , non-static member functions, based on the object only exists with inheritance, essentially covering.

 

 

Implementation Mechanism virtual functions:

Dynamic binding implementation mechanism VTABLE
The compiler creates a virtual function for each class contains a virtual function table VTABLE , each of the table points to the address of a virtual function, i.e., can be viewed as an array of VTABLE table function pointers, each entry is the address of the virtual function element of the array.
 
Each class has its own virtual function containing a virtual function table of VTABLE. VTABLE each derived class inherits its respective base class VTABLE, if a group contains a class VTABLE (entry address of the virtual function), the VTABLE its derived class will contain the same one, but two the values ​​may be different.
 
If the derived class overrides the corresponding virtual function, derived after such point is overloaded VTABLE class virtual functions, if not to redefine the virtual function corresponding to the derived class, the base class is used this virtual function address.
 

When creating an object class contains a virtual function, the compiler may add an entry in the pointer memory layout vptr each object, a pointer to the class VTABLE present. When the base class through a pointer to an object (referred to as bp) calls a virtual function, the compiler generates code is acquired first referents vtb1 pointer, and then call the corresponding entry points VTABLE vtb1 class (specifically, virtual function the entry address).

 

When the base class is not defined virtual functions , its length = length of data members; derived class length = length + data member itself base class data members inherited length;

When the base class in the virtual function defined , the members of which length = length + data length of the address of the virtual function table; address length = length of the derived class itself base class data member length + length + data members inherited virtual function tables.

Contains a virtual function and a length of several increments class virtual function is zero. Class has virtual functions simply adds the first address pointer for storing a virtual function table.

The derived class virtual function in the base class of the same name have the same index number (or serial number) in the VTABLE.

 

 

Virtual function limitations:

In addition to virtual functions adds some extra resource overhead, no harm.

 

note:

  1. Only member functions can be declared as virtual function, not an ordinary function.
  2. Virtual function must be non-static member function. Because static member function is not limited to an object.
  3. Inline function is not declared virtual. Because inline functions can not be dynamically determined in the running position.
  4. Constructor can not be virtual. Polymorphism is a value different objects have different behavior of the same message, mainly for object constructors are run before generation of the object, meaningless.

 

 

One problem: the constructor can call a virtual function? why?

Calling virtual functions at runtime decision.
However, for the case to call a virtual function in the constructor, to be called just a local version of this function. In other words, a virtual mechanism does not work in the constructor.
 
1. From grammatically, call no problem.
2. In effect, however, often can not achieve the required purposes.

Effective explanation is:
when entering the base class constructor during derived object constructor, the type of the object into a base type, instead of a derived class type.
Also, when entering the base class destructor, the object is the base type.
 
Therefore, the virtual function always just call virtual base class (if it is to call the base class virtual function), can not achieve the effect of multi-state, so in the constructor does not make sense, but often can not achieve the effect originally intended.
 
 
In addition:
 
 

 

 
 
 
 
 

Second problem: the need to declare the destructor as virtual function? why?

This involves a concept: virtual destructor, visible destructor is declared as virtual functions.

When required virtual destructor:

We need to remove the derived class objects through a base class pointer , just prior to adding virtual base class destructor

It can be credited directly: destructor should be virtual, unless the base class class do not.

 

Controlled trials, an ordinary destructor:

#include <iostream>
using namespace std;

class A{
      public: ~A(){ cout<<"A::~A is called"<<endl; } }; class B:public A{ public: ~B(){ cout<<"B::~B is called"<<endl; } }; int main(){ A *ap = new B; B *bp = new B; 
    cout<<"First Delete"<<endl;
    delete ap; cout<<"Second Delete"<<endl; delete bp;
getchar(); }

When seen Class A Class B pointer to the object, it performed only Class A destructor;

When a pointer to the Class B Class B object, execute the destructor of the derived class B, then the base class destructor performs the A.

 

Control experiment, two, virtual destructor:

#include <iostream>
using namespace std;

class A{
      public: virtual ~A(){ cout<<"A::~A is called"<<endl; } }; class B:public A{ public: ~B(){ cout+<<"B::~B is called"<<endl; } }; int main(){ A *ap = new B; B *bp = new B; cout<<"First Delete"<<endl; delete ap; cout<<"Second Delete"<<endl; delete bp; getchar(); }

 

Plus a virtual, what is the point of the object, which object destructor will be executed . So that the derived class objects can call the destructor properly under different conditions.

 

Why virtual destructor:

Excerpt from C ++ Prime 5

 


 

 

Abstract classes and pure virtual functions

What is: the specific operation contents are not defined in the base class, this time should be illustrated as a function of a pure virtual function, specific operation by the descendant class definition, a class with a pure virtual function to be an abstract class.

Achieved: virtual return type of the function name (parameter list) = 0;

Use: You can declare a pointer to the abstract class and references, and access point to a derived class object.

Note: If the derived class implements all abstract pure virtual function members of the class, the derived class can declare its own object, no longer is an abstract class; on the contrary, is still derived class is an abstract class.

 

Guess you like

Origin www.cnblogs.com/sialianzi/p/11424495.html