C + + language Learning (11)--polymorphism

Source: Internet
Author: User

C + + language Learning (11)--polymorphic One, polymorphic introduction

Polymorphism (polymorphism) in C + + refers to the different classes that are generated by inheritance and whose objects respond differently to the same message.
Polymorphism is an important feature of object-oriented programming, which can increase the flexibility of the program. Can reduce the workload and complexity of system upgrades, maintenance, commissioning.
Polymorphism is an important link under different levels of classification, and it is a kind of cross-layer operation.

Second, the precondition of multi-state realization

Assignment-compatible rules are alternatives to objects of a public-derived class that can be used anywhere a base class object is needed.
Assignment compatibility is a default behavior that does not require any explicit conversion steps and can only occur in the public inheritance mode, which is a precondition for polymorphic implementations.
The overrides referred to in the assignment compatibility rule include the following:
A, subclass object can be directly assigned to the parent class object
B, subclass object can initialize parent class object directly
C, the parent class reference can directly reference the child class object
D, the parent class pointer can point directly to the subclass object
When you use a parent class pointer (reference) to point to a child object, the subclass object is degraded to the parent class object, only members defined in the parent class can be accessed, and members of the same name overridden by the quilt class are accessed directly.

  #include <iostream>using namespace Std;class parent{public:int m;    Parent (int a) {m = A;    } void Print () {cout << "Parent m =" << m << Endl;    }};class child:public parent{public:int m;    Child (int a):P arent (a) {m = A;    } void Print () {cout << "child m =" << m << Endl;    }};int Main () {Parent p (0);    Child C (0);    Parent P1 (c); parent* PP = &c;//The parent class pointer to the subclass object is degraded to the parent class object parent& RP = c;//The parent class reference to the child class object is degraded to the parent class object Pp->print (); Parent m = 0 rp.print ();    Parent m = 0//child cc = static_cast<child> (p);//requires conversion constructor to support child* pc = static_cast<child*> (&p); Pc->print ();//child m = xxxx return 0;}  

When overridden, a derived class object can be used as an object of the base class, but only members that inherit from the base class are used.
The parent class can also be converted to subclasses by a strong transition, but there is a risk of cross-border access.
A subclass can redefine a member function that already exists in the parent class, that is, the function override.
When a function override encounters assignment compatibility, the compiler can only judge the object to which it is pointing based on the type of the pointer, and according to the assignment compatibility principle, the compiler considers the parent pointer to be the parent class object and can only invoke a function of the same name defined in the parent class.
In object-oriented programming, it is often necessary to determine how to invoke an overriding function based on the actual object type. When the parent class pointer points to the parent class object, the function defined by the parent class is called, and when the parent pointer points to a child class object, the function defined by the child class is called, and the function defined by the parent class object is called when the parent class references the parent class object, and the function defined by the child class is called when the parent class references

Conditions for formation of polymorphic states 1, polymorphism

The function that is called depends on the actual object type pointed to by the parent class pointer, which is polymorphic. In Polymorphic, the parent class pointer (reference) to the parent class object invokes the function defined in the parent class, and the parent class pointer (reference) refers to the child class object when the function is called.
C + + uses the virtual keyword to support polymorphism, and a function that is declared by virtual is rewritten with a polymorphic attribute.
Conditions for polymorphic formation:
A, there is a virtual function in the parent class.
B, subclass Override (overwrite) the virtual function in the parent class.
C, through the Quilt class object assignment of the parent class pointer, call the common interface.

2. Virtual function

The declaration syntax for a virtual function is as follows:

virtual 函数声明;

The rules for using the

virtual function are as follows:
A, in the parent class, declare the member function as a virtual function. When you implement virtual functions outside of a class, you do not have to add virtual.
B, in a derived class, redefining a member function that already exists in the parent class is called a function override, requires a function name, a return value type, a function parameter number and a type all match, and redefine the function body according to the needs of the derived class.
C, when a member function is declared as a virtual function, the exact same function in its derived class is also a virtual function, and the virtual function in the derived class can be added to the virtual keyword or not.
D, defining a parent class object pointer to an object of its child class, calling a virtual function from a parent class pointer, at which point a function with the same name as the subclass is called.
E, the constructor cannot be a virtual function, and the virtual function table pointer can be initialized correctly after the constructor has finished executing. Destructors can be virtual functions, define a parent class pointer and use new to create a subclass object initialization, use Delete to release the heap space of the parent class pointer, only call the parent class's destructor, do not call the child class's destructor, will cause a memory leak, the parent class destructor declared as virtual function can avoid the problem. In general, you need to declare a destructor as a virtual function. When the constructor executes, the virtual function table pointer is not initialized correctly, so the constructor cannot be polymorphic, and when the destructor function executes, the virtual function table pointer has been destroyed, so the destructor is unlikely to occur polymorphic. Only the version of the function defined in the current class can be called in constructors and destructors.

#include <iostream>using namespace std;class Parent{public:    int mi;    void add(int i)    {        mi += i;    }    void add(int a, int b)    {        mi += (a + b);    }    virtual void print()    {        cout << "Parent" << endl;    }};class Child : public Parent{public:    int mi;    //函数重写    void add(int x, int y)    {        mi += (x + y);    }    //函数重写    void print()    {        cout << "Child" << endl;    }};int main(int argc, char *argv[]){    Child child;    child.add(1,2);//调用子类函数    child.Parent::add(1);//调用父类函数    child.Parent::add(1,2);//调用父类函数    Parent p = child;    p.add(1);    p.add(1,2);    Parent& rp = child;    rp.add(1);    rp.add(1,2);    rp.print();//Child    Parent* pp = &child;    pp->add(1);    pp->add(1,2);    pp->print();//Child    return 0;}
3. Pure virtual function

The declaration syntax for a pure virtual function is as follows:

virtual 函数声明 = 0;

The rules for using pure virtual functions are as follows:
A, a class containing pure virtual function, called abstract base class, not instantiated, that is, cannot create an object, the meaning of existence is to be inherited, to provide a common interface of the class family, called interface in Java.
B, pure virtual function only declaration, not implemented.
C, if a pure virtual function is declared in a class, and a pure virtual function is not implemented in a derived class, the virtual function is still a pure virtual function in the derived class, and the derived class is still the abstract base class.

4. Rules for the use of virtual functions

The rules for using virtual functions are as follows:
A, only member functions of a class can be declared as virtual functions. Virtual functions only apply to class objects that have an inheritance relationship, so ordinary functions cannot be declared as virtual functions.
B, a static member function cannot be a virtual function. Static member functions are not bound by objects, only information of the class.
C, an inline function cannot be a virtual function.
D, the constructor cannot be a virtual function. When constructed, the creation of an object has not yet completed. Once the construction is complete, a veritable object can be counted.
E, destructors can be virtual functions and are generally declared as virtual functions
F, a class that contains virtual functions, and destructors must also be declared as virtual functions. The destructor of the subclass is called when the delete parent pointer is in the class.

Iv. the meaning of polymorphism

The meanings of polymorphism are as follows:
A, the dynamic characteristics of the program during the operation of the show
B, the function rewrite must be polymorphic implementation, otherwise there is no meaning
C, polymorphism is the basic characteristic of object-oriented component programming
D, polymorphism is a cross-layer operation
Static linking is the ability to determine specific function calls during the compilation of a program, such as function overloading.
Dynamic linking is the ability to determine specific function calls, such as function overrides, when the program is actually running.

#include <iostream>using namespace std;class Parent{public:    int mi;    virtual void add(int i)    {        mi += i;    }    virtual void add(int a, int b)    {        mi += (a + b);    }    virtual void print()    {        cout << "Parent" << endl;    }};class Child : public Parent{public:    int mi;    //函数重写    void add(int x, int y)    {        mi += (x + y);    }    //函数重写    void print()    {        cout << "Child" << endl;    }};int main(int argc, char *argv[]){    Child child;    child.add(1,2);//静态联编    child.Parent::add(1);//静态联编    child.Parent::add(1,2);//静态联编    Parent p = child;    p.add(1);//静态联编    p.add(1,2);//静态联编    p.print();//静态联编    cout << endl;    Parent& rp = child;    rp.add(1);//静态联编    rp.add(1,2);//动态联编    rp.print();//动态联编    Parent* pp = &child;    pp->add(1);//静态联编    pp->add(1,2);//动态联编    pp->print();//动态联编    return 0;}

C + + language Learning (11)--polymorphism

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.