Pin-Jiun / Programming-Language-CPP

It's the note/experience about C++, and I have the basic ability of C.
0 stars 0 forks source link

4-Polymorphism #5

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

Function Binding

function內容是在compile時決定

function內容是在程式 執行 時決定 Polymorphism基本上支持dynamic binding, 其關鍵字是 virtual

基本的多型

#include <iostream>
using namespace std;

class Student{
public:
    void Hello(){   //add virtual
        cout << "I'm a student.\n";
    }
};

class ChemsitryStudent : public Student{
public:
    void Hello(){
        cout << "I'm a student major in chemistry.\n";
    }
};

int main()
{
    Student Amy;
    Amy.Hello();

    ChemsitryStudent Jim;
    Jim.Hello();
}

此時雖然method相同,但會依照其object的class去呼叫其method

I'm a student.
I'm a student major in chemistry.