preface

Having been around Java for a long time, we all know that, as a typical representative of the object-oriented camp, encapsulation, inheritance, polymorphism (and, indeed, abstraction) are its three basic characteristics

But what exactly is polymorphism, how does it work at the bottom, and what are its strengths and weaknesses, may not be so easy to articulate

Today we are going to take a look at its close relative, C++, what is polymorphism

Next, the body begins!

What is polymorphism

Polymorphism is one of the three fundamental characteristics of object orientation. Polymorphism is the encapsulation of a data model as a class of objects in an object-oriented context. Objects can have different derived classes. The use of different derived classes that have different behaviors is called polymorphism

How is polymorphism implemented

From the language level, polymorphism depends on object-oriented inheritance (Implement) and function rewriting to implement, a base class can be derived from different subclass objects, different subclass objects can have their own different behavior, just as the dragon gives birth to nine children, phoenix gives birth to nine young

From the compiler’s point of view, polymorphism depends on different derived classes having the same pointer type, so when a class is created, it can point to its base class

Further, functions of derived and base classes have a virtual function table (Vtable) to store their Pointers so that subclasses can inherit and call members of the base class, as shown below

Image from JerryFu’s blog >>> www.cnblogs.com/jerry-fuyi/…

What are the benefits of polymorphism

We often emphasize programming to the interface/programming to the superclass, a well-defined base class that basically doesn’t need to be modified, only the behavior of different derived classes

Therefore, when we need to change the specific behavior at the invocation level, we can modify the derived class or recreate a derived class to meet the business needs

The calling layer only needs to change the original derived class to the derived class we recreated to achieve the effect of the corresponding requirements with minimal code changes

What are the disadvantages of polymorphism

The disadvantage of polymorphism is that its simulation of real world objects can have the consequence of inconsistent behavior when the base class definition is inaccurate

For example, we define a base class Bird. According to common sense, flight is the basic ability of birds, so we define a function fly().

Different birds may have their own different behavior, we define a derived class Ostrich (Ostrich), but the Ostrich cannot fly, which leads to the result that the behavior of the derived class is inconsistent with that of the base class

This problem is not solved by polymorphism, so we must patch the polymorphism in other forms, that is, through function rewriting, to change the base class method, implement the derived class’s own behavior; But what function rewriting does not solve is the confusion of business logic caused by inconsistent behavior when calling at the calling layer, which requires more code to modify the calling layer

So when we define base classes, try to think clearly about which functions are common and need to be placed in the base class to reduce this occurrence

Polymorphic notation

Let’s take a look at the code for C++ polymorphism

Source please see >>>Github.com/liyilin-jac…

When God created human beings, he also used object-oriented thinking

God first defines a base class Human, which has virtual functions pee() and walk(), which are assigned to the derived classes to implement. Since all humans can crawl, the crawling function is directly implemented here

#include <string>
#include <vector>

using namespace std;

class Human{
    
public:
    string name = "";
    int age = 1;
    
    Human(){
    };
    
    
    virtual void pee(a){};virtual void walk(a){};void crawl(a){
        printf("%s crawing... \n",name.c_str());
    };
    
    
};
Copy the code

Class Baby (); class Baby (); class Baby (); class Baby ();

class Baby:public Human{
    
public:
    Baby() {};Baby(string name){
        this->name = name;
    };
    
    ~Baby() {delete &name;
        delete &age;
    };
    
    void pee(a) override{
        if ((age)<3) {
            printf("%s pee with it's parents help... \n",name.c_str());
        }else{
            printf("%s pee by itself... \n",name.c_str()); }}void walk(a) override{
        if ((age)<2) {
            printf("%s can't walk yet... \n",name.c_str());
        }else{
            printf("%s walking... \n",name.c_str()); }}};Copy the code

God created a derived class Man, which also implements pee() and walk functions based on the actual scenario

class Man:public Human{
public:
    Man(a);Man(string name,int age){
        this->name = name;
        this->age = age;
    }
    
    void walk(a) override{
        printf("%s walking... \n",name.c_str());
    }
    
    void pee(a) override{
        printf("%s pee by standing... \n",name.c_str()); }};Copy the code

With Man, create a Woman! So humans can reproduce on their own

class Woman:public Human{
public:

    vector<Baby*> *babys = new vector<Baby*>(10);
    
    Woman(a);Woman(string name,int age){
        this->name = name;
        this->age = age;
    }

    Baby* haveABaby(Man* man,string name);

    void walk(a) override{
        printf("%s walking... \n",name.c_str());
    }
    void pee(a) override{
        printf("%s pee by sitting... \n",name.c_str()); }};Baby* Woman::haveABaby(Man* man,string name){
    Baby *baby = NULL;
    if (man) {
        baby = new Baby(name);
        babys->push_back(baby);
    }
    return baby;
}
Copy the code

Now that the humans are done, it’s time to put them to work. Now open the human world.

void createWorld(a);

int main(int argc, const char * argv[]) {
    createWorld(a);return 0;
}

void createWorld(a){
    //create Adam
    Human* Adam = new Man("Adam".18);
    Adam->walk(a); Adam->pee(a);//create Eve
    Human* Eve = new Woman("Eve".16);
    Eve->walk(a); Eve->pee(a);//Adam meet Eve
    //Eve have a baby Gain
    string name_gain = "Gain";
    Human *Gain =  ((Woman*)Eve)->haveABaby((Man*)Adam,name_gain);
    Gain->walk(a); Gain->pee(a); Gain->crawl(a);//Eve have a baby Abel
    string name_abel = "Abel";
    Human *Abel =  ((Woman*)Eve)->haveABaby((Man*)Adam,name_abel);
    Abel->age = 4;
    Abel->walk(a); Abel->pee(a); Abel->crawl(a); }Copy the code

Adam and Eve ate the forbidden fruit and gave birth to two children, Gain and Abel

Since then, human beings have lived and multiplied

Afterword.

The above is my recent experience of learning C++, if you have different views, or experience, please continue to discuss in the comments

I am relieved. See you in the next article!