14. C++ Polymorphism

content

polymorphism concept

Polymorphism

abstract class

The principle of polymorphism


polymorphism concept

What is polymorphism?

It is to produce different results for the same method interface for different objects. Just like the popular red envelopes, different people (objects) grab red envelopes (method interfaces) for different money (different results).

Polymorphism

The composition of polymorphism needs to meet two conditions:
1. The virtual function must be called through the pointer or reference of the base class.
2. The called function must be a virtual function, and the derived class must override the virtual function of the base class.

class PersonA
{
public:
    virtual void LuckmMoney()
    {
      cout<<"抢到1/3"<<endl;
    }
};

class PersonB:public PersonA
{
public:
    virtual void LuckmMoney()
    {
      cout<<"抢到2/3"<<endl;
    }
};

void Func(PersonA& people)
{
    People.LuckmMoney();
}

void Test()
{
    personA zhangyi;
    Func(zhangyi);
    personB goucui;
    Func(goucui);
}

The virtual modified class member functions are called virtual functions.

The implementation of polymorphism uses the rewriting (overriding) of virtual functions, and there is a virtual function in the derived class that is exactly the same as the base class, which constitutes rewriting.

We also have two keywords to remember

1. final: Modifies a virtual function, indicating that the virtual function can no longer be inherited

2. override: Check whether the derived class virtual function overrides a base class virtual function, if not, a compilation error will be reported.

abstract class

Add =0 after the virtual function, then the function is a pure virtual function, and the class containing the pure virtual function is an abstract class.

After the derived class inherits, it must be rewritten to instantiate the object, which reflects the interface inheritance.

The principle of polymorphism

If there is a virtual function in a class, there will be a virtual function table to store the pointer to the virtual function, and the class will store the pointer to the virtual function table.

The essence of the principle of polymorphism is the rewriting of virtual functions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324304151&siteId=291194637